vue实现通讯
Vue 组件通讯方法
父子组件通讯
父组件向子组件传递数据通过 props,子组件向父组件传递数据通过 $emit 事件。
父组件模板:
<child-component :message="parentMessage" @update="handleUpdate"></child-component>
子组件代码:
props: ['message'],
methods: {
sendToParent() {
this.$emit('update', newValue)
}
}
兄弟组件通讯
通过共同的父组件作为中介,或者使用 Event Bus。
创建 Event Bus:
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
组件A发送事件:
EventBus.$emit('event-name', data)
组件B接收事件:
EventBus.$on('event-name', data => {
// 处理数据
})
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)
provide/inject
适合祖先组件向后代组件跨层级传递数据。
祖先组件:
provide() {
return {
theme: 'dark'
}
}
后代组件:
inject: ['theme']
$attrs/$listeners
处理未声明 props 和事件的传递。
父组件:
<child-component v-bind="$attrs" v-on="$listeners"></child-component>
$parent/$children
直接访问父/子组件实例(不推荐常用)。
this.$parent.someMethod()
this.$children[0].someData






