Vue2:Provide/Inject
Provide/Inject
//父组件 <template> <div> <p>{{ title }}</p> <son></son> </div> </template>
<script> import Son from "./son" export default { name: 'Father', components: { Son }, // provide选项提供变量 provide: { message: 'provided by father' }, data () { return { title: '父组件' } }, methods: { ... } } </script> //中间组件 <template> <div> <p>{{ title }}</p> <grand-son></grand-son> </div> </template>
<script> import grandSon from "./grandSon " export default { name: "Son", components: { grandSon }, data () { return { title: '子组件' } }, }; </script>
//中间组件的嵌套组件 <template> <div> <p>message:{{ message }}</p> </div> </template>
<script> export default { name: "GrandSon", inject: [ "message" ], data () { return { title: '孙组件' } }, methods: { ... } }; </script>