vue父子通信如何实现
父子组件通信方法
Props 传递数据
父组件通过 props 向子组件传递数据。子组件中声明 props 接收父组件传递的值。
父组件模板:
<child-component :message="parentMessage"></child-component>
子组件代码:
props: ['message']
$emit 触发事件
子组件通过 $emit 触发自定义事件,父组件通过 v-on 监听并处理。
子组件代码:
this.$emit('update', newValue)
父组件模板:
<child-component @update="handleUpdate"></child-component>
高级通信方式
v-model 语法糖
实现父子组件的双向绑定,本质是 props + $emit 的封装。
父组件模板:
<child-component v-model="value"></child-component>
子组件代码:
model: {
prop: 'value',
event: 'input'
},
props: ['value']
$refs 访问实例
父组件通过 ref 属性获取子组件实例,直接调用方法或访问数据。
父组件代码:

this.$refs.child.methodName()
$parent/$children
子组件通过 $parent 访问父实例,父组件通过 $children 访问子实例(不推荐,耦合性高)。
跨级通信方案
provide/inject
祖先组件通过 provide 提供数据,后代组件通过 inject 注入使用。
祖先组件代码:
provide() {
return {
theme: this.themeData
}
}
后代组件代码:
inject: ['theme']
事件总线 创建空的 Vue 实例作为中央事件总线,实现任意组件间通信。
全局总线:

const bus = new Vue()
Vue.prototype.$bus = bus
组件发送事件:
this.$bus.$emit('event-name', data)
组件接收事件:
this.$bus.$on('event-name', data => {})
状态管理方案
Vuex 集中管理 复杂应用建议使用 Vuex 进行状态管理,实现全局数据共享。
store 定义:
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) {
state.count++
}
}
})
组件提交变更:
this.$store.commit('increment')
组件访问状态:
this.$store.state.count






