父组件:html
<script>
import Children from '@/components/children.vue'
export default {
name: 'home',
components: {
Children
},
provide(){
return {
value:"来自app"
}
}
}
复制代码
子组件(后代组件):vue
<template>
<div>
{{value}}
</div>
</template>
<script>
export default {
inject:["value"]
}
</script>
复制代码
父组件经过provide将value这个变量提供给它的全部的子组件,而子组件经过inject访问这个变量。bash
须要注意的是:provide 和 inject 绑定并非可响应的。这是刻意为之的。然而,若是你传入了一个可监听的对象,那么其对象的属性仍是可响应的。app
因此父组件的value若是改变了,子组件的value是不会改变的。ide
provide和inject怎么实现数据响应式:函数
通常来讲,有两种办法:优化
// A 组件
<div>
<h1>A 组件</h1>
<button @click="() => changeColor()">改变color</button>
<ChildrenB />
<ChildrenC />
</div>
......
data() {
return {
color: "blue"
};
},
// provide() {
// return {
// theme: {
// color: this.color //这种方式绑定的数据并非可响应的
// } // 即A组件的color变化后,组件D、E、F不会跟着变
// };
// },
provide() {
return {
theme: this//方法一:提供祖先组件的实例
};
},
methods: {
changeColor(color) {
if (color) {
this.color = color;
} else {
this.color = this.color === "blue" ? "red" : "blue";
}
}
}
// 方法二:使用2.6最新API Vue.observable 优化响应式 provide
// provide() {
// this.theme = Vue.observable({
// color: "blue"
// });
// return {
// theme: this.theme
// };
// },
// methods: {
// changeColor(color) {
// if (color) {
// this.theme.color = color;
// } else {
// this.theme.color = this.theme.color === "blue" ? "red" : "blue";
// }
// }
// }
复制代码
// F 组件
<template functional>
<div class="border2">
<h3 :style="{ color: injections.theme.color }">F 组件</h3>
</div>
</template>
<script>
export default {
inject: {
theme: {
//函数式组件取值不同
default: () => ({})
}
}
};
</script>
复制代码
参考网址:www.cnblogs.com/fundebug/p/…ui