使用vue实例实现通信
Vue 实例通信方法
父子组件通信
使用 props 传递数据给子组件,子组件通过 $emit 触发事件传递数据给父组件。
父组件:
<template>
<ChildComponent :message="parentMessage" @update="handleUpdate" />
</template>
<script>
export default {
data() {
return {
parentMessage: 'Hello from parent'
}
},
methods: {
handleUpdate(newMessage) {
this.parentMessage = newMessage
}
}
}
</script>
子组件:
<template>
<button @click="sendMessage">Send Message</button>
</template>
<script>
export default {
props: ['message'],
methods: {
sendMessage() {
this.$emit('update', 'New message from child')
}
}
}
</script>
兄弟组件通信
通过共享的父组件作为中介,或者使用事件总线。
事件总线方法:
// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
组件A:
import { EventBus } from './event-bus.js'
EventBus.$emit('message', 'Hello from A')
组件B:
import { EventBus } from './event-bus.js'
EventBus.$on('message', (msg) => {
console.log(msg)
})
跨层级组件通信
使用 provide/inject 实现祖先组件向后代组件传递数据。
祖先组件:
export default {
provide() {
return {
sharedData: this.sharedData
}
},
data() {
return {
sharedData: 'Shared information'
}
}
}
后代组件:
export default {
inject: ['sharedData'],
created() {
console.log(this.sharedData)
}
}
Vuex 状态管理
对于复杂应用,使用 Vuex 集中管理状态。
store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
组件中使用:
this.$store.commit('increment')
console.log(this.$store.state.count)
$refs 直接访问
通过 ref 属性直接访问组件实例或DOM元素。
<template>
<ChildComponent ref="child" />
<button @click="callChildMethod">Call Child Method</button>
</template>
<script>
export default {
methods: {
callChildMethod() {
this.$refs.child.childMethod()
}
}
}
</script>






