所谓数据注入,是指父组件可以向其所有子组件提供数据,不论在层级结构上此子组件的层级有多深。

实现数据注入需要使用组件的provideinject两个配置项,提供数据的父组件需要设置provide配置项来提供数据,子组件需要设置inject配置项来获取数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<body>
<div id="Application">
<my-list :count="5">
</my-list>
</div>
<script>
const App = Vue.createApp({})
const listCom = {
props:{
count: Number
},
provide(){
return {
listCount:this.count
}
},
template:`
<div style="border:red solid 10px;">
<my-item v-for="i in this.count" :index="i"></my-item>
</div>
`
}
const itemCom = {
props: {
index:Number
},
template:`
<div style="border:blue solid 10px;"><my-label :index="this.index"></my-label></div>
`
}
const labelCom = {
props: {
index:Number
},
inject:['listCount'],
template:`
<div>{{index}}/{{this.listCount}}</div>
`
}
App.component("my-list", listCom)
App.component("my-item", itemCom)
App.component("my-label", labelCom)
App.mount("#Application")
</script>
</body>