传值: 父组件 => 子组件 => 孙组件
// 父组件
<template><div class="app"><h3>我是app组件(祖) --- {{ name }} {{ price }}</h3><child /></div>
</template><script>
import { reactive, toRefs, provide } from "vue";
import child from "./components/child.vue";export default {name: "App",components: { child },setup() {let car = reactive({ name: "奔驰", price: "40W" });// 给自己的后代组件传递数据,只要在这里执行了provide,后代子组件都可以通过inject获取数据// 父传子props 父传孙provideprovide("car", car);return {...toRefs(car),};},
};
</script><style>
.app {background-color: #ccc;padding: 10px;
}
</style>
<template><div class="child"><h3>我是child组件(子) {{ msg }}{{ school }}</h3><son/></div>
</template><script>
// import { ref } from "vue";
import son from './son.vue'
export default {name: "child",components: { son },props: ["msg", "school","afanfan"],setup() {return {};},
};
</script><style>.child {background-color: skyblue;padding: 10px;}
</style>
// 孙组件
<template><div class="son"><h3>我是son组件(孙)--- {{ car.name }}--- {{ car.price }}</h3></div>
</template><script>
import { inject } from "vue";
export default {name: "son",setup() {let car = inject("car")return {car,};},
};
</script><style>
.son {background-color: orange;padding: 10px;
}
</style>
更多的组件传值传事件请参考:
vue3传值传事件参考