vue祖孙组件传值(组件三层嵌套传值方法)
通过provide/inject可以轻松实现跨级访问祖先组件的数据先看代码实现效果吧父组件 index.vue<template><!-- 父组件 --><div class="views__home"><my-children></my-children></div></template><script&g
·
通过provide/inject可以轻松实现跨级访问祖先组件的数据
先看代码实现效果吧
父组件 index.vue
<template>
<!-- 父组件 -->
<div class="views__home">
<my-children></my-children>
</div>
</template>
<script>
import MyChildren from './my-children.vue'; // 子组件
export default {
components: {
MyChildren
},
provide() {
return {
student: {
name: 'xiaoming'
}
};
},
mounted() {
console.log(this.student); // undefined
}
};
</script>
子组件 my-children.vue
<template>
<!-- 子组件 -->
<div class="views__home__my-children">
<my-grandson></my-grandson>
</div>
</template>
<script>
import MyGrandson from './my-grandson.vue'; // 孙组件
export default {
components: {
MyGrandson
}
};
</script>
孙组件 my-grandson.vue
<template>
<!-- 孙组件 -->
<div class="views__home__my-grandson"></div>
</template>
<script>
export default {
inject: ['student'],
mounted() {
console.log(this.student); // { name : 'xiaoming' }
}
};
</script>
可以看出来 my-grandson组件可以直接获取到 index组件传过来的变量,中间不在需要经过 my-children组件
需注意:父组件中无法对provide()中的student进行数据更新操作,可换做如下写法:
props方式(三级嵌套)
孙组件:想要接收的参数写入props
子组件:
父组件:直接动态绑定
更多推荐
已为社区贡献4条内容
所有评论(0)