Vue 3 中的 provide 和 inject 跨组件通讯

在 Vue 3 中,provideinject 的使用方式略有不同,但依然提供了强大的功能来实现跨组件通信。

1. 祖先组件提供数据

在祖先组件中使用 provide 提供数据。

示例
  1. 祖先组件(GrandparentComponent.vue)
1<template>
2  <div>
3    <button @click="changeValue">改变值</button>
4    <parent-component />
5  </div>
6</template>
7
8<script setup>
9import ParentComponent from './ParentComponent.vue';
10
11const value = ref('这是来自祖先组件的数据');
12
13const changeValue = () => {
14  value.value = '更新后的数据';
15};
16
17provide('sharedValue', value);
18</script>
2. 后代组件注入数据

在后代组件中使用 inject 注入数据。

示例
  1. 父组件(ParentComponent.vue)
1<template>
2  <div>
3    <child-component />
4  </div>
5</template>
6
7<script setup>
8import ChildComponent from './ChildComponent.vue';
9</script>
  1. 子组件(ChildComponent.vue)
1<template>
2  <div>
3    <p>{{ sharedValue }}</p>
4  </div>
5</template>
6
7<script setup>
8const sharedValue = inject('sharedValue');
9
10console.log(sharedValue); // 输出:这是来自祖先组件的数据
11</script>

更复杂的示例

下面是一个更复杂的示例,展示了如何在多个组件之间传递数据,并在组件内部进行响应式更新。

示例
  1. 祖先组件(GrandparentComponent.vue)
1<template>
2  <div>
3    <button @click="changeValue">改变值</button>
4    <parent-component />
5    <p>当前值:{{ value }}</p>
6  </div>
7</template>
8
9<script setup>
10import ParentComponent from './ParentComponent.vue';
11import { ref } from 'vue';
12
13const value = ref('这是来自祖先组件的数据');
14
15const changeValue = () => {
16  value.value = '更新后的数据';
17};
18
19provide('sharedValue', value);
20</script>
  1. 父组件(ParentComponent.vue)
1<template>
2  <div>
3    <child-component />
4  </div>
5</template>
6
7<script setup>
8import ChildComponent from './ChildComponent.vue';
9</script>
  1. 子组件(ChildComponent.vue)
1<template>
2  <div>
3    <p>{{ sharedValue }}</p>
4  </div>
5</template>
6
7<script setup>
8import { inject, watch } from 'vue';
9
10const sharedValue = inject('sharedValue');
11
12console.log(sharedValue); // 输出:这是来自祖先组件的数据
13
14// 监听共享值的变化
15watch(sharedValue, (newValue) => {
16  console.log('共享值变化:', newValue);
17});
18</script>

注意事项

  1. 注入默认值

    • 可以为 inject 提供默认值,以防注入的数据未被提供。
    • 示例:const sharedValue = inject('sharedValue', '默认值').
  2. 注入非响应式数据

    • 如果注入的数据不是响应式的,可以使用 reactive 或者 ref 包装数据。
    • 示例:provide('sharedValue', reactive({ data: '这是数据' })).
  3. 命名空间冲突

    • 如果多个组件使用相同的注入键名,可能会导致命名空间冲突。可以通过命名空间或其他方式避免冲突。
    • 示例:provide('appSharedValue', value).
  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值