Vue · 19/70
1. Composition API 逻辑复用 2. 微信小程序与 Vue 的区别 3. React Fiber 架构与 Vue 的设计差异 4. 渐进式框架的理解 5. React 和 Vue 的技术差异 6. React 和 Vue 的区别 7. setup 中获取组件实例 8. SPA 首屏加载优化 9. 单页应用如何提高加载速度 10. 模板预编译原理 11. 什么是虚拟DOM 12. Vite 的实现原理 13. VNode 的属性 14. Vue 组件中的原生事件监听器需要手动销毁吗 15. Vue 数组元素修改与视图更新 16. Vue 项目中封装 axios 17. 打破 Vue scoped 样式隔离 18. Vue 组件和插件的区别 19. Vue 组件通信方式 20. 虚拟 DOM 的实现原理 21. Computed 与 Watch 对比 22. Vue 项目跨域解决方案 23. Vue CSS scoped 的实现原理 24. Vue 组件渲染过程 25. Vue 自定义指令的使用场景 26. Vue data 为什么必须是函数 27. Vue 项目部署与 404 问题解决 28. Vue 组件错误统一监听 29. Vue Diff 算法:Vue2 vs Vue3 30. 手写 Vue 事件机制 31. Vue 中定义全局方法 32. Vue 框架理解 33. Vue.nextTick 原理与应用 34. Vue Mixin 的理解与应用 35. Vue2 对象新增属性不响应 36. Vue.observable 实现响应式状态管理 37. Vue 父组件监听子组件生命周期 38. Keep-Alive 实现原理 39. Vue 生命周期钩子 40. Vue 项目优化实践 41. Vue 性能优化 42. Vue 权限管理实现方案 43. Vue 大型项目的结构和组件划分 44. ref、toRef、toRefs 的区别与使用场景 45. Vue 渲染过程 46. Vue-Router 路由模式原理 47. Vue SSR 服务器端渲染实现 48. v-for 中 key 的作用 49. Vue slot 插槽的使用 50. Vue 模板编译原理 51. v-model 参数用法 52. v-if 与 v-show 区别 53. Vue 版本性能分析 54. Vue 1.x 响应式系统 55. Vue 2.x 响应式系统与组件更新 56. Vue2 数组变化检测的限制与解决方案 57. Vue2 响应式原理 58. Composition API vs Options API 59. Vue3 设置全局变量 60. watch 与 watchEffect 的区别 61. Vue3 响应式原理与优势 62. Vue 3 Proxy 响应式与性能优化 63. Vue3 实现 Modal 组件 64. Vuex 辅助函数的使用 65. Vue 3 的 Tree Shaking 特性 66. Vuex 数据刷新丢失问题 67. Vue3 新特性 68. Vuex 与 Pinia 状态管理 69. Vuex 的五种属性及其作用 70. Vuex 是什么?

Vue 组件通信方式

Props、Emit、EventBus、Vuex/Pinia、Provide/Inject 等组件通信方案

问题

Vue 中组件之间如何通信?常见的通信方式有哪些?

解答

1. Props / Emit(父子通信)

最基础的通信方式,父传子用 props,子传父用 emit。

<!-- Parent.vue -->
<template>
  <Child :message="msg" @update="handleUpdate" />
</template>

<script setup>
import { ref } from 'vue'
import Child from './Child.vue'

const msg = ref('Hello')

const handleUpdate = (newValue) => {
  msg.value = newValue
}
</script>
<!-- Child.vue -->
<template>
  <div>
    <p>{{ message }}</p>
    <button @click="emit('update', 'New Value')">更新</button>
  </div>
</template>

<script setup>
// 定义 props
defineProps({
  message: String
})

// 定义 emit
const emit = defineEmits(['update'])
</script>

2. Provide / Inject(跨层级通信)

祖先组件提供数据,后代组件注入使用,无需逐层传递。

<!-- Ancestor.vue -->
<script setup>
import { provide, ref } from 'vue'

const theme = ref('dark')

// 提供响应式数据
provide('theme', theme)

// 提供修改方法
provide('updateTheme', (newTheme) => {
  theme.value = newTheme
})
</script>
<!-- Descendant.vue -->
<script setup>
import { inject } from 'vue'

// 注入数据,第二个参数是默认值
const theme = inject('theme', 'light')
const updateTheme = inject('updateTheme')

// 使用
updateTheme('light')
</script>

3. EventBus(任意组件通信)

Vue 3 移除了 $on,需要使用第三方库如 mitt。

// eventBus.js
import mitt from 'mitt'

export const emitter = mitt()
<!-- ComponentA.vue -->
<script setup>
import { emitter } from './eventBus'

// 发送事件
const sendMessage = () => {
  emitter.emit('custom-event', { data: 'Hello' })
}
</script>
<!-- ComponentB.vue -->
<script setup>
import { onMounted, onUnmounted } from 'vue'
import { emitter } from './eventBus'

const handler = (payload) => {
  console.log(payload.data)
}

onMounted(() => {
  // 监听事件
  emitter.on('custom-event', handler)
})

onUnmounted(() => {
  // 移除监听,防止内存泄漏
  emitter.off('custom-event', handler)
})
</script>

4. Pinia(全局状态管理)

Vue 3 推荐的状态管理方案,替代 Vuex。

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  
  getters: {
    doubleCount: (state) => state.count * 2
  },
  
  actions: {
    increment() {
      this.count++
    }
  }
})
<!-- 任意组件中使用 -->
<script setup>
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()

// 读取状态
console.log(counter.count)
console.log(counter.doubleCount)

// 修改状态
counter.increment()
counter.count++
counter.$patch({ count: 10 })
</script>

5. $attrs(透传属性)

未被 props 声明的属性会自动透传,适合封装组件。

<!-- MyInput.vue -->
<template>
  <!-- $attrs 自动包含未声明的属性 -->
  <input v-bind="$attrs" :value="modelValue" @input="onInput" />
</template>

<script setup>
// 只声明需要处理的 props
defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])

const onInput = (e) => {
  emit('update:modelValue', e.target.value)
}
</script>

<script>
export default {
  // 禁止自动继承到根元素
  inheritAttrs: false
}
</script>
<!-- 使用时 -->
<template>
  <!-- placeholder、disabled 等会透传到 input -->
  <MyInput v-model="text" placeholder="请输入" disabled />
</template>

6. $parent / $refs(直接访问实例)

直接访问父组件或子组件实例,不推荐常用。

<!-- Parent.vue -->
<template>
  <Child ref="childRef" />
</template>

<script setup>
import { ref, onMounted } from 'vue'

const childRef = ref(null)

onMounted(() => {
  // 访问子组件暴露的方法
  childRef.value.sayHello()
})
</script>
<!-- Child.vue -->
<script setup>
const sayHello = () => {
  console.log('Hello from child')
}

// 必须显式暴露,否则父组件无法访问
defineExpose({
  sayHello
})
</script>

通信方式选择

场景推荐方式
父子组件Props / Emit
跨多层组件Provide / Inject
兄弟组件EventBus 或状态管理
全局状态Pinia
组件封装透传$attrs
直接调用子组件方法$refs + defineExpose

关键点

  • Props 向下传递,Emit 向上传递,是最基础的父子通信方式
  • Provide/Inject 解决跨层级传递问题,但要注意响应式数据需要用 ref/reactive
  • Vue 3 中 EventBus 需要用 mitt 等第三方库,记得在 onUnmounted 中移除监听
  • Pinia 是 Vue 3 官方推荐的状态管理,比 Vuex 更简洁
  • $attrs 配合 inheritAttrs: false 可以精确控制属性透传
  • 使用 $refs 访问子组件时,子组件必须用 defineExpose 暴露方法