方法一
通过父组件provide返回函数数据,然后在子组件内通过computed计算属性对函数进行返回
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| parent.vue <template> <button @click="handleClick">change</button> </template> export default { data() { return { num: 0, }; }, provide() { return { cNum: () => { return this.num; }, }; }, methods: { handleClick() { this.num++; }, }, }
child.vue <template> <div class="">子组件{{ num }}</div> </template> export default { computed: { num(){ return this.cNum() } }, inject: ["cNum"], };
|
方法二
父组件通过provide传递对象类型的响应数据,子组件接收会使其变成响应式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| parent.vue <template> <button @click="handleClick">change</button> </template> export default { data() { return { obj:{ num: 0 } }; }, provide() { return { cNum: this.obj, }; }, methods: { handleClick() { this.obj.num++; }, }, }
child.vue <template> <div class="">子组件{{ cNum.num }}</div> </template> export default { inject: ["cNum"], };
|