注释很详细,直接上代码
上一篇
新增内容
- 祖先组件向下传值
- 子代组件接受数据
源码
App.vue
<template>
<div id="app">
<sonComponent></sonComponent>
</div>
</template>
<script>
import sonComponent from "./components/sonComponents.vue";
export default {
name: "App",
components: {
sonComponent,
},
//温馨提醒,该属性不具备响应式
//传递给后代的数据(这种方法无法直接使用data的数据)
/*provide:{
name:'代码对我眨眼睛111',
age:18
},*/
//传递给后代的数据(这种方法可以使用data的数据)
//使用时需注意结构
provide() {
return{
providedData: this.providedData,
}
},
data() {
return {
name: "代码对我眨眼睛",
age: 38
};
},
computed:
{
providedData() {
return {
name: this.name,
age: this.age,
};
},
},
methods: {},
};
</script>
<style></style>
sonComponents.vue
<template>
<div>
<h1>子组件</h1>
<p>姓名:{{ providedData.name }}</p>
<grandsonComponent></grandsonComponent>
</div>
</template>
<script>
import grandsonComponent from "./grandsonComponents.vue";
export default {
components: {
grandsonComponent,
},
//注入父组件的name属性(即接收祖先组件传下来的数据)
inject: ["providedData"],
};
</script>
<style lang="less" scoped></style>
grandsonComponents.vue
<template>
<div>
<h3>孙组件</h3>
<p>年龄:{{providedData.age}}</p>
</div>
</template>
<script>
export default {
// 注入父组件的属性
inject:["providedData"]
}
</script>
<style lang="less" scoped>
</style>
效果演示