vue provide和inject 父组件和子孙通信

父组件中通过provider来提供变量,然后在子组件中通过inject来注入变量。不论子组件有多深,只要调用了inject那么就可以注入provider中的数据。而不是局限于只能从当前父组件的prop属性来获取数据,只要在父组件的生命周期内,子组件都可以调用。

child:

<template>
<div>
<p>{{message}}</p>

</div>
</template>

<script>
export default {
name: "childThree",
inject: ['for'],
data(){
return {
message:this.for,
}
}
}
</script>
parents:
<template>
<div>
<p>this is parent compoent!</p>
<child-two></child-two>
</div>
</template>

<script>
import childTwo from '../components/childThree'
export default {
name: "parentTwo",
provide:{
for:'test'
},
components:{
childTwo
}
}
</script>

<style scoped>

</style>

猜你喜欢

转载自www.cnblogs.com/zhx119/p/10594536.html