项目场景:
当vue文件中存在多级的父子组件传值、多个子组件或孙子级组件都要使用顶级或父级的数据时,使用provide 和 inject 组合出现一个问题,只是注入的初始值,并不能随时拿到数据源的实时更新。
示例代码
祖先级
<template>
<div>
<testNum :comNum="comNum"/>
<el-button @click="changeCompName">改变comNum</el-button>
</div>
</template>
<script>
import testNum from './testNum';
export default {
data () {
return {
comNum: 0
};
},
components: {
testComp
},
methods: {
changeComNum () {
this.comNum ++;
},
},
provide () {
return {
comNum: this.comNum,
};
},
};
</script>
<style scoped>
</style>
父级
<template>
<div>
<div>父----- {{ comNum }}</div>
<child/>
</div>
</template>
<script>
import child from './child';
export default {
name: 'testCom',
props: {
comNum: {
type: Number,
}
},
components: {
child
},
};
</script>
<style scoped>
</style>
子孙级
<template>
<div>孙子-----{{ comNum }}</div>
</template>
<script>
export default {
name: 'child',
inject: [ 'comNum' ],
};
</script>
<style scoped>
</style>
解决方案:
1、在provide时,返回一个方法,方法中 return 目标数据
provide () {
return {
getComNum: () => this.comNum,
};
},
2、在inject后,使用计算属性computed计算出一个新值
<template>
<div>孙子-----{{ compNum }}</div>
</template>
<script>
export default {
name: 'child',
inject: [ 'getComNum' ],
computed: {
compNum () {
return this.getComNum();
}
}
};
</script>
<style scoped>
</style>