Vue 提供了多种组件通信方式,适用于不同场景的需求。以下是主要的通信方式:
1. 父子组件通信
1.1 Props 向下传递
// 父组件
<ChildComponent :message="parentMessage" />
// 子组件
props: {
message: String
}
1.2 自定义事件向上传递
// 子组件
this.$emit('event-name', data)
// 父组件
<ChildComponent @event-name="handleEvent" />
1.3 v-model 双向绑定
// 父组件
<ChildComponent v-model="value" />
// 子组件
props: ['value'],
methods: {
updateValue(newValue) {
this.$emit('input', newValue)
}
}
1.4 .sync 修饰符 (Vue 2.x)
// 父组件
<ChildComponent :title.sync="doc.title" />
// 子组件
this.$emit('update:title', newTitle)
1.5 parent 和parent和children (不推荐)
// 访问父组件
this.$parent.someMethod()
// 访问子组件
this.$children[0].someMethod()
1.6 Refs (获取子组件实例)
// 父组件
<ChildComponent ref="child" />
// 访问子组件
this.$refs.child.someMethod()
1.7 作用域插槽
// 子组件
<slot :user="user"></slot>
// 父组件
<ChildComponent>
<template v-slot:default="slotProps">
{{ slotProps.user.name }}
</template>
</ChildComponent>
2. 祖 孙/后代组件通信
Provide/Inject
// 祖先组件
provide() {
return {
theme: this.theme
}
}
// 后代组件
inject: ['theme']
3. 全局事件总线(兄弟组件、无关联组件)
// 创建事件总线 (通常在 main.js)
Vue.prototype.$bus = new Vue()
// 组件A 发送事件
this.$bus.$emit('event-name', data)
// 组件B 接收事件
this.$bus.$on('event-name', (data) => {
// 处理数据
})
// 记得在组件销毁前移除监听
beforeDestroy() {
this.$bus.$off('event-name')
}
4. Vuex 状态管理(适用于大型应用中的全局状态管理)
// 存储状态
this.$store.commit('mutationName', payload)
// 获取状态
this.$store.state.moduleName.stateName
// 异步操作
this.$store.dispatch('actionName', payload)
5. attrs 和attrs和listeners (Vue 2.x)
// 父组件
<ChildComponent v-bind="$attrs" v-on="$listeners" />