vue父子组件如何实现
vue父子组件通信方法
父组件向子组件传递数据 使用props属性实现父组件向子组件传递数据。父组件通过v-bind绑定数据,子组件通过props接收。
父组件模板:
<child-component :message="parentMessage"></child-component>
子组件代码:
export default {
props: ['message']
}
子组件向父组件传递数据 通过$emit触发自定义事件实现子组件向父组件通信。子组件触发事件,父组件监听并处理。
子组件代码:
this.$emit('update', newValue)
父组件模板:
<child-component @update="handleUpdate"></child-component>
使用ref直接访问子组件 父组件可以通过ref属性直接访问子组件的属性和方法。
父组件模板:
<child-component ref="childRef"></child-component>
父组件脚本:
this.$refs.childRef.childMethod()
使用v-model实现双向绑定 通过model选项和v-model指令实现父子组件数据的双向绑定。
子组件代码:
export default {
model: {
prop: 'value',
event: 'input'
},
props: ['value']
}
父组件模板:

<child-component v-model="parentData"></child-component>
使用.sync修饰符 Vue提供的.sync修饰符可以简化双向绑定的实现方式。
父组件模板:
<child-component :title.sync="pageTitle"></child-component>
子组件代码:
this.$emit('update:title', newTitle)
使用provide/inject 祖先组件通过provide提供数据,后代组件通过inject注入数据,适合跨多级组件通信。
祖先组件代码:
export default {
provide() {
return {
theme: this.themeData
}
}
}
后代组件代码:

export default {
inject: ['theme']
}
使用事件总线 创建全局事件总线实现任意组件间通信,适合非父子关系的组件。
创建事件总线:
export const EventBus = new Vue()
发送事件:
EventBus.$emit('eventName', payload)
接收事件:
EventBus.$on('eventName', payload => {})
使用Vuex状态管理 对于复杂应用,建议使用Vuex集中管理组件共享状态。
安装Vuex后:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
组件中使用:
this.$store.commit('increment')
console.log(this.$store.state.count)
每种方法适用于不同场景,根据具体需求选择合适的方式。简单父子通信推荐props/$emit,跨多级组件考虑provide/inject,复杂状态管理使用Vuex更合适。






