允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深(这也是使用$parent不好实现的地方),并在起上下游关系成立的时间里始终生效。
不用再关心dom层级,只要在祖先组件内部就可以一直使用祖先组件提供的provide
provide 选项允许我们指定我们想要提供给后代组件的数据/方法。
然后在任何后代组件里,我们都可以使用 inject 选项来接收指定的我们想要添加在这个实例上的属性:
祖先组件不需要知道哪些后代组件使用它提供的属性
后代组件不需要知道被注入的属性来自哪里
provide/inject 是解决组件之间的通信问题的利器,不受层级结构的限制,但并不是响应式的。
但也不是随便去滥用,通信代表着耦合:
demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="dynamic-component-demo">
<google-map style="border:1px solid pink;">
<google-map-region v-bind:shape="cityBoundaries" style="border:1px solid red;width:80%;">
<google-map-markers v-bind:places="iceCreamShops" style="border:1px solid yellow;width:60%;"></google-map-markers>
</google-map-region>
</google-map>
</div>
<script>
Vue.component('google-map', {
template: `
<div>
<h1 @click="changeMsg">我是祖父,googel-map,{{msg}}</h1>
<div>改变msg<input type=“text” v-model="msg" /></div>
<slot></slot>
</div>`,
data(){
return {
msg:'你好,我是devincob'
}
},
provide: function () {
return {
getMap: function(){
console.log('我来自祖父组件',this.msg)
},
msg:this.msg
}
},
methods:{
changeMsg(){
this.msg = 'hello,i am devincob!'
}
}
})
Vue.component('google-map-region', {
props:["shape"],
inject: ['getMap','msg'],
template: `
<div>
<h2 @click="getMap">我是父亲,gooel-map-region,{{msg}}</h2>
<p>{{shape}}</p>
<slot></slot>
</div>
`
})
Vue.component('google-map-markers', {
props:["places"],
inject: ['getMap','msg'],
template: `<div>
<h3 @click="getMap">我是儿子,gooel-map-makers,{{msg}}</h3>
<p>{{places}}</p>
</div>`
})
new Vue({
el: '#dynamic-component-demo',
data: {
currentTab: 'Posts',
tabs: ['Posts', 'Archive'],
msg:'恭喜您中了我司一等奖,devincon!',
cityBoundaries:'上海',
iceCreamShops:'莲花超市'
},
computed: {
currentTabComponent: function () {
return 'tab-' + this.currentTab.toLowerCase()
}
}
})
</script>
</body>
</html>