vue实现父子通讯
Vue 父子组件通信实现方法
父组件向子组件传递数据(Props)
父组件通过props向子组件传递数据。子组件需要在props选项中声明接收的属性。
父组件模板:
<template>
<child-component :message="parentMessage" />
</template>
子组件接收:
export default {
props: ['message'],
// 或带类型验证
props: {
message: {
type: String,
required: true
}
}
}
子组件向父组件发送事件($emit)
子组件通过$emit触发事件,父组件通过v-on监听这些事件。
子组件触发:
this.$emit('update', newValue)
父组件监听:
<template>
<child-component @update="handleUpdate" />
</template>
使用v-model实现双向绑定
通过v-model可以实现父子组件的双向数据绑定。
子组件需要:
export default {
model: {
prop: 'value',
event: 'input'
},
props: ['value']
}
父组件使用:
<child-component v-model="parentData" />
使用.sync修饰符(Vue 2.x)
.sync修饰符是另一种双向绑定的实现方式。
父组件:
<child-component :title.sync="pageTitle" />
子组件更新:

this.$emit('update:title', newTitle)
使用$refs访问子组件
父组件可以通过$refs直接访问子组件的属性和方法。
父组件:
<child-component ref="child" />
this.$refs.child.childMethod()
使用$parent/$children
子组件可以通过$parent访问父组件实例,父组件可以通过$children访问子组件实例。
子组件访问父组件:
this.$parent.parentMethod()
Provide/Inject(跨层级通信)
祖先组件通过provide提供数据,后代组件通过inject注入数据。
祖先组件:
provide() {
return {
theme: this.themeData
}
}
后代组件:

inject: ['theme']
Event Bus(全局事件总线)
创建一个空的Vue实例作为中央事件总线,实现任意组件间通信。
创建event bus:
export const EventBus = new Vue()
组件A发送事件:
EventBus.$emit('event-name', data)
组件B接收事件:
EventBus.$on('event-name', data => {
// 处理数据
})
Vuex状态管理
对于复杂的应用状态管理,可以使用Vuex进行集中式状态管理。
安装Vuex后:
// store.js
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
组件中使用:
this.$store.commit('increment')
console.log(this.$store.state.count)
注意事项
- 优先使用props/$emit进行基础通信
- 简单场景使用v-model或.sync
- 跨层级组件使用provide/inject
- 复杂应用考虑使用Vuex
- 避免过度使用$parent/$children,会使组件耦合度过高






