依赖注入的数据可以被所有的后代组件访问到
父组件代码
<template>
<div class="clickD" @click="clickF"></div>
<HelloWorld />
</template>
<script>
// 引入子组件
import HelloWorld from './components/HelloWorld.vue';
export default {
name: 'App',
// 将数据注入到后代组件中
provide() {
return {
todoL: this.todoList
}
},
data() {
return {
todoList: {
test: 'test'
}
}
},
components: {
// 注册子组件
HelloWorld
},
methods: {
clickF() {
this.todoList.test = 'test123';
}
}
}
</script>
<style>
body {
margin: 0px;
padding: 0px;
}
.clickD {
width: 100px;
height: 100px;
background: red;
}
</style>
子组件代码
<template>
<div>{{todoL}}</div>
<HC />
</template>
<script>
// 引入子组件
import HC from './HC.vue';
export default {
// 获取注入的数据
inject: {
todoL: {
default: '123', // 添加默认值
}
},
data() {
return {
}
},
methods: {
},
components: {
// 注册子组件
HC
},
}
</script>
<style scoped>
.hello {
width: 100px;
height: 100px;
background: red;
}
</style>
子组件的子组件代码
<template>
<div>{{todoL}}--HC</div>
</template>
<script>
export default {
// 获取注入的数据
inject: {
todoL: {
default: '456', // 添加默认值
}
}
}
</script>
<style>
</style>