vue中的provide/inject的学习使用

irst:定义一个parent component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
 <div>
<childOne></childOne>
 </div>
</template>
 
<script>
 import childOne from '../components/test/ChildOne'
 export default {
  name: "Parent",
  provide: {
   for: "demo"
  },
  components:{
   childOne
  }
 }

在这里我们在父组件中provide for这个变量。

second 定义一个子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
 <div>
  {{demo}}
  <childtwo></childtwo>
 </div>
</template>
 
<script>
 import childtwo from './ChildTwo'
 export default {
  name: "childOne",
  inject: ['for'],
  data() {
   return {
    demo: this.for
   }
  },
  components: {
   childtwo
  }
 }
</script>

third 定义另一个子组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
 <div>
  {{demo}}
 </div>
</template>
 
<script>
 export default {
  name: "",
  inject: ['for'],
  data() {
   return {
    demo: this.for
   }
  }
 }
</script>

在2个子组件中我们使用jnject注入了provide提供的变量for,并将它提供给了data属性。

这里官网注明例子只工作在 Vue 2.2.1 或更高版本。低于这个版本时,注入的值会在 props 和 data 初始化之后得到。

运行之后看下结果

从上面这个例子可以看出,只要在父组件中调用了,那么在这个父组件生效的生命周期内,所有的子组件都可以调用inject来注入父组件中的值。

原文地址:https://www.cnblogs.com/love314159/p/9089141.html