provide 与 inject"/>
vue3中的provide 与 inject
一、概述
作用:实现祖先与后代组件的通信。一般为祖孙通信,因为子组件可以用props来通信。
语法:父组件中:provide('car', car) 子组件中:let car = inject('car')
二、举例说明(代码如下)
(1)目录结构
(2)parentView.vue(provide传递数据)
<template><div class="parent"><h2>父组件:{{ name }}---{{ price }}</h2><Child></Child></div>
</template><script>
import { provide, reactive, toRefs } from 'vue';
import Child from './childView.vue'export default {components: {Child},setup() {let car = reactive({name: '法拉利',price: '20K'})// provide传递数据provide('car', car)return {...toRefs(car)}}
}
</script><style>
.parent {padding: 10px;background-color: skyblue;
}
</style>
(3)childView.vue
<template><div class="child"><h2>子组件:{{ name }}---{{ price }}</h2><Sun></Sun></div>
</template><script>
import Sun from './sunView.vue'
export default {components: {Sun},setup() {}
}
</script><style>
.child {padding: 10px;background-color: skyblue;
}
</style>
(4)sunView.vue(inject接收数据)
<template><div class="sun"><h2>孙组件:{{ car.name }}---{{ car.price }}</h2></div>
</template><script>
import { inject } from 'vue';export default {setup() {// inject 接收数据let car = inject('car')return {car}}
}
</script><style>
.sun {padding: 10px;background-color: pink;
}
</style>
三、最终效果展示
更多推荐
vue3中的provide 与 inject
发布评论