vue实现组件传递数据
父子组件数据传递
在Vue中,父组件向子组件传递数据主要通过props实现。父组件通过v-bind绑定数据,子组件通过props接收。
父组件模板:
<child-component :message="parentMessage"></child-component>
子组件接收:
props: {
message: {
type: String,
required: true
}
}
子父组件通信
子组件向父组件传递数据使用$emit触发自定义事件。父组件通过v-on监听这些事件。
子组件触发:
this.$emit('update', newValue)
父组件监听:
<child-component @update="handleUpdate"></child-component>
兄弟组件通信
当两个组件没有直接父子关系时,可以通过共同父组件作为中介,或者使用事件总线/Vuex。
事件总线方式:

// eventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
// 组件A发送
EventBus.$emit('event-name', data)
// 组件B接收
EventBus.$on('event-name', data => {
// 处理数据
})
provide/inject
跨层级组件通信可以使用provide/inject这对API。祖先组件提供数据,后代组件注入使用。
祖先组件:
provide() {
return {
sharedData: this.someData
}
}
后代组件:
inject: ['sharedData']
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)
非父子组件直接访问
通过ref属性可以获取组件实例实现直接访问。
父组件:
<child-component ref="child"></child-component>
获取子组件实例:
this.$refs.child.someMethod()






