vue实现父子组件
Vue 父子组件通信实现方法
父组件向子组件传递数据(Props)
在父组件中通过v-bind或简写:向子组件传递数据。子组件通过props接收数据。
父组件模板:
<template>
<child-component :message="parentMessage" />
</template>
子组件接收:
export default {
props: {
message: {
type: String,
required: true
}
}
}
子组件向父组件传递数据(自定义事件)
子组件通过$emit触发自定义事件,父组件通过v-on或简写@监听事件。
子组件触发:
this.$emit('update', newValue)
父组件监听:
<template>
<child-component @update="handleUpdate" />
</template>
使用v-model实现双向绑定
子组件需要声明model选项并处理value属性和input事件。
子组件实现:
export default {
model: {
prop: 'value',
event: 'input'
},
props: ['value'],
methods: {
updateValue(newVal) {
this.$emit('input', newVal)
}
}
}
父组件使用:
<child-component v-model="parentData" />
使用$refs访问子组件
父组件可以通过ref属性直接访问子组件实例和方法。

父组件设置ref:
<child-component ref="childRef" />
父组件调用方法:
this.$refs.childRef.childMethod()
使用provide/inject跨层级通信
适用于深层嵌套组件,祖先组件提供数据,后代组件注入使用。
祖先组件:
export default {
provide() {
return {
sharedData: this.sharedData
}
}
}
后代组件:
export default {
inject: ['sharedData']
}
使用事件总线(Event Bus)
创建单独的Vue实例作为中央事件总线,实现任意组件间通信。

创建事件总线:
export const eventBus = new Vue()
发送事件:
eventBus.$emit('event-name', data)
接收事件:
eventBus.$on('event-name', data => {
// 处理数据
})
使用Vuex状态管理
对于复杂应用,使用Vuex集中管理组件共享状态。
store定义:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
组件中使用:
this.$store.commit('increment')
console.log(this.$store.state.count)






