企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
* provide 和 inject 提供依赖注入,功能类似 vue2.x 的 provide/inject。 * 实现跨层级组件间通信。祖组件可以直接与子孙组件通信,不再需要通过父组件。 ![](https://img.kancloud.cn/ef/6f/ef6fb23833d3a488a5bb1d1a033e6ed4_1547x448.png) **1. 祖组件`src/components/LearnProvideInjectParent.vue`** ```html <template> <h1>祖组件</h1> <button @click="update">更新</button> <h3>{{ num }}</h3> <hr /> <!-- 2. 祖组件中引入父组件 --> <LearnProvideInjectParent></LearnProvideInjectParent> </template> <script lang="ts"> import { defineComponent, provide, ref } from 'vue' import LearnProvideInjectParent from './LearnProvideInjectParent.vue' export default defineComponent({ name: 'LearnProvideInjectGrand', setup() { const num = ref(0) const update = () => { num.value++ } //1. 调用provide提供一个num属性 provide('num', num) return { num, update, } }, components: { LearnProvideInjectParent, }, }) </script> ``` **2. 父组件`src/components/LearnProvideInjectGrandSon.vue`** ```html <template> <h1>父组件</h1> <hr /> <!-- 1. 父组件中引入子孙组件 --> <LearnProvideInjectGrandSon></LearnProvideInjectGrandSon> </template> <script lang="ts"> import { defineComponent } from 'vue' import LearnProvideInjectGrandSon from './LearnProvideInjectGrandSon.vue' export default defineComponent({ name: 'LearnProvideInjectParent', setup() { console.log('') }, components: { LearnProvideInjectGrandSon, }, }) </script> ``` **3. 子孙组件`src/components/LearnProvideInjectGrandSon.vue`** ```html <template> <h1>子孙组件</h1> <h3>{{ num }}</h3> </template> <script lang="ts"> import { defineComponent, inject } from 'vue' export default defineComponent({ name: 'LearnProvideInjectGrandSon', setup() { //1. 调用inject获取祖组件中的num属性值 const num = inject('num') return { num, } }, }) </script> ``` **4. 效果** 可见,祖组件可以跨过父组件直接给子孙组件传递数据。 ![](https://img.kancloud.cn/f2/f7/f2f747747cc95dc2e65f3a58bc9e66d3_1703x525.gif)