相信你们在工做中必定遇到过多层嵌套组件,而vue 的组件数据通讯方式又有不少种。css
好比vuex、$parent与$children、prop、$emit与$on、$attrs与$lisenters、eventBus、ref。vue
今天主要为你们分享的是provide
和inject
。vuex
不少人会问,那我直接使用vuex不就好了吗?数组
vuex当然是好!bash
可是,有可能项目自己并无使用vuex的必要,这个时候provide
和inject
就闪亮登场啦~ide
选项应该是一个对象或返回一个对象的函数。该对象包含可注入其子孙的property
。函数
能够是一个字符串数组、也能够是一个对象ui
说白了,就是provide
在祖先组件中注入,inject
在须要使用的地方引入便可。this
咱们能够把依赖注入看作一部分大范围的prop
,只不过它如下特色:spa
祖先组件不须要知道哪些后代组件使用它提供的属性
后代组件不须要知道被注入的属性是来自那里
index.vue
<template>
<div class="grandPa">
爷爷级别 : <strong>{{ nameObj.name }} 今年 <i class="blue">{{ age }}</i>岁, 城市<i class="yellow">{{ city }}</i></strong>
<child />
<br>
<br>
<el-button type="primary" plain @click="changeName">改变名称</el-button>
</div>
</template>
<script>
import child from '@/components/ProvideText/parent'
export default {
name: 'ProvideGrandPa',
components: { child },
data: function() {
return {
nameObj: {
name: '小布'
},
age: 12,
city: '北京'
}
},
provide() {
return {
nameObj: this.nameObj, //传入一个可监听的对象
cityFn: () => this.city, //经过computed来计算注入的值
age: this.age //直接传值
}
},
methods: {
changeName() {
if (this.nameObj.name === '小布') {
this.nameObj.name = '貂蝉'
this.city = '香港'
this.age = 24
} else {
this.nameObj.name = '小布'
this.city = '北京'
this.age = 12
}
}
}
}
</script>
<style lang="scss" scoped>
.grandPa{
width: 600px;
height:100px;
line-height: 100px;
border: 2px solid #7fffd4;
padding:0 10px;
text-align: center;
margin:50px auto;
strong{
font-size: 20px;
text-decoration: underline;;
}
.blue{
color: blue;
}
}
</style>
复制代码
parent.vue
<template>
<div class="parent">
父亲级别 : <strong>只用做中转</strong>
<son />
</div>
</template>
<script>
import Son from './son'
export default {
name: 'ProvideParent',
components: { Son }
}
</script>
<style lang="scss" scoped>
.parent{
height:100px;
line-height: 100px;
border: 2px solid #feafef;
padding:0 10px;
margin-top: 20px;
strong{
font-size: 20px;
text-decoration: underline;;
}
}
</style>
复制代码
son.vue
<template>
<div class="son">
孙子级别 : <strong>{{ nameObj.name }} 今年 <i class="blue">{{ age }}</i>岁, 城市<i class="yellow">{{ city }}</i></strong>
</div>
</template>
<script>
export default {
name: 'ProvideSon',
//inject 来获取的值
inject: ['nameObj', 'age', 'cityFn'],
computed: {
city() {
return this.cityFn()
}
}
}
</script>
<style lang="scss" scoped>
.son{
height:100px;
line-height: 100px;
padding:0 10px;
margin: 20px;
border: 1px solid #49e2af;
strong{
font-size: 20px;
text-decoration: underline;;
}
.blue{
color: blue;
}
}
</style>
复制代码
咱们来看一下运行结果。
图一:未点击【改变名称】按钮,原有状态
图二:已经点击【改变名称】按钮,更新后状态
你们能够对比一下先后差别。
会发现一个小细节。
不管我点击多少次,孙子组件的年龄age
字段永远都是12
并不会发生变化。
正是官网所提到的provide
和 inject
绑定并非可响应的。这是刻意为之的。
因此你们使用的时候,必定要注意注入的方式,否则极可能没法实现数据响应。
但愿今天的分享对你能有所帮助~