官网中有介绍provide / inject可以实现对于父组件横跨多个子组件的传值方法,如以下代码:
先看模拟图(父组给组件4传递数据):
父组件代码:
<template>
<div id="home">
<div class="fu">
<h1>这是父组件</h1>
<button @click="add">改变msg的值</button>
<A></A>
</div>
</div>
</template>
<script>
import A from '../components/a'
export default {
name: 'Home',
components:{
A
},
/*
为了使其组件4接收到的数据事响应式的,这里data里面需要抛出一个对象
*/
provide(){
return{
dvalue: this.dvalue
}
},
data(){
return{
dvalue:{
num:10
},
}
},
methods:{
add(){
setInterval(()=>{
this.dvalue.num++
},1000)
}
}
}
</script>
<style scoped>
.fu{
width: 800px;
height: 800px;
text-align: center;
}
</style>
子组件:
<template>
<div id="d">
这是子组件4--{{dvalue.num}}
</div>
</template>
<script>
export default {
name: "b",
inject:['dvalue']
}
</script>
<style scoped>
#d{
width: 80px;
height: 60px;
margin: 0 auto;
border: 3px solid blue;
text-align: center;
}
</style>
这样子,传值已经完毕,组件1、2、3里面不需要写任和操作,只需要在需要接受数据的组件中写inject就可以了。代码是不是简介了好多