上个月,我们重构一个老项目,发现一个"祖传组件":
- 父组件传 props 给子组件
- 子组件再传给孙子
- 孙子改了个状态,通过
$emit一层层往上抛 - 中间任意一层改名,整条链就断了......
同事苦笑:"这哪是组件通信,这是传话游戏。"
其实,Vue 3 早就提供了更优雅、更健壮 的通信方案。
今天我就用 4 种场景 + 对应解法,帮你彻底告别"props drilling"和"emit 地狱"。
先看一张决策图(建议收藏)
| 场景 | 推荐方案 |
|---|---|
| 父 ↔ 子 | props + emit(基础但够用) |
| 跨多层(祖孙) | provide / inject |
| 兄弟 or 任意组件 | 组合式函数(Composable)+ 响应式状态 |
| 复杂全局状态(用户、主题、权限) | Pinia(官方推荐) |
注意:不是所有通信都要用 Pinia! 小范围状态用轻量方案更干净。
姿势 1:父子通信 ------ 老老实实用 props/emit(但要规范)
这是最基础的,但很多人写得乱:
反面教材:
html
<!-- Child.vue -->
<script setup>
const emit = defineEmits(['update-name', 'save', 'cancel', 'validate']);
// 4 个 emit?这个组件到底负责什么?
</script>
正确做法:单一职责 + 语义化命名
html
<!-- UserForm.vue -->
<script setup>
const props = defineProps<{ modelValue: string }>();
const emit = defineEmits<{ (e: 'update:modelValue', val: string): void }>();
const localValue = ref(props.modelValue);
watch(() => props.modelValue, v => localValue.value = v);
const handleChange = () => {
emit('update:modelValue', localValue.value); // 使用 v-model 语法糖
};
</script>
技巧:用
v-model代替自定义update-xxx,模板更简洁:
html<UserForm v-model="userName" />
姿势 2:祖孙通信 ------ 用 provide / inject 跳过中间层
当你需要从 App.vue 直接传数据到深度嵌套的 Button 组件,别再层层传 props!
ts
// App.vue
import { provide, ref } from 'vue';
const theme = ref<'light' | 'dark'>('light');
provide('THEME', theme); // 提供响应式数据
html
<!-- DeepChildButton.vue -->
<script setup>
import { inject } from 'vue';
const theme = inject('THEME'); // 自动获得响应性!
</script>
<template>
<button :class="theme">Click me</button>
</template>
关键点:
- 如果
provide的是ref或reactive,inject拿到的就是响应式的- 可以配合 TypeScript 定义 InjectionKey,避免字符串魔法值
ts
// types.ts
import { InjectionKey, Ref } from 'vue';
export const THEME_KEY: InjectionKey<Ref<'light' | 'dark'>> = Symbol('theme');
姿势 3:任意组件通信 ------ 用 Composable 封装共享状态(90% 的人不知道!)
这是 Vue 3 最被低估的能力!
想象:两个不相关的弹窗,需要共享"是否正在提交"状态。
错误做法:把状态提到父组件,或滥用 Pinia
正确做法:写一个 useSubmitState composable:
ts
// composables/useSubmitState.ts
import { ref } from 'vue';
const isSubmitting = ref(false);
export function useSubmitState() {
const start = () => isSubmitting.value = true;
const end = () => isSubmitting.value = false;
return { isSubmitting, start, end };
}
然后在任意组件中使用:
html
<!-- ModalA.vue -->
<script setup>
import { useSubmitState } from '@/composables/useSubmitState';
const { isSubmitting, start } = useSubmitState();
const handleSubmit = () => {
start();
// ...提交逻辑
};
</script>
html
<!-- ModalB.vue -->
<script setup>
import { useSubmitState } from '@/composables/useSubmitState';
const { isSubmitting } = useSubmitState(); // 实时同步!
</script>
优势:
- 零依赖(不用 Pinia)
- 天然响应式
- 可测试、可复用
- 作用域清晰(只在需要的组件引入)
姿势 4:全局状态 ------ 交给 Pinia,别自己造轮子
当状态涉及:
- 用户登录信息
- 全局主题/语言
- 跨路由的数据缓存
这时候就该用 Pinia(Vuex 的继任者,Vue 官方推荐):
ts
// stores/user.ts
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', () => {
const profile = ref(null);
const isLoggedIn = computed(() => !!profile.value);
const login = async (credentials) => {
profile.value = await api.login(credentials);
};
return { profile, isLoggedIn, login };
});
在组件中:
ts
const userStore = useUserStore();
userStore.login({ email, password });
Pinia 优势:
- Composition API 风格
- 完美 TS 支持
- DevTools 调试友好
- 服务端渲染(SSR)兼容
总结:什么时候用哪种?
| 需求 | 推荐方案 | 是否响应式 | 适用规模 |
|---|---|---|---|
| 父子简单传值 | props / emit | ✅ | 小 |
| 跨层级传配置 | provide / inject | ✅ | 中 |
| 局部共享状态 | Composable + ref | ✅ | 小~中 |
| 全局业务状态 | Pinia | ✅ | 大 |
不要:
- 用
$parent/$children(破坏封装)- 用 EventBus(Vue 3 已废弃)
- 所有状态都塞进 Pinia(过度设计)
最后说两句
组件通信不是技术难题,而是架构选择题 。
用对了工具,代码像乐高一样拼接;用错了,就成了意大利面条。
记住:能局部解决的,别全局化;能轻量实现的,别上重型库。
各位互联网搭子,要是这篇文章成功引起了你的注意,别犹豫,关注、点赞、评论、分享走一波,让我们把这份默契延续下去,一起在知识的海洋里乘风破浪!