在Vue.js框架中,組件通信是一個核心概念,它允許組件之間共享數據和狀態。以下是Vue.js中常見的組件通信方式:
<!-- 父組件 -->
<template>
<ChildComponent :message="parentMessage" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from parent'
};
}
};
</script>
<!-- 子組件 -->
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: {
message: String
}
};
</script>
<!-- 子組件 -->
<template>
<button @click="sendMessageToParent">Send to Parent</button>
</template>
<script>
export default {
methods: {
sendMessageToParent() {
this.$emit('message-to-parent', 'Hello from child');
}
}
};
</script>
<!-- 父組件 -->
<template>
<ChildComponent @message-to-parent="handleMessageFromChild" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleMessageFromChild(message) {
console.log(message); // 'Hello from child'
}
}
};
</script>
// store.js
import { createStore } from 'vuex';
export default createStore({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
increment({ commit }) {
commit('increment');
}
},
getters: {
count: state => state.count
}
});
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
const app = createApp(App);
app.use(store);
app.mount('#app');
<!-- 任何組件 -->
<template>
<div>{{ count }}</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: {
...mapState(['count'])
},
methods: {
...mapActions(['increment'])
}
};
</script>
<!-- 祖先組件 -->
<script>
export default {
provide() {
return {
globalMessage: 'Hello from ancestor'
};
}
};
</script>
<!-- 后代組件 -->
<script>
export default {
inject: ['globalMessage'],
mounted() {
console.log(this.globalMessage); // 'Hello from ancestor'
}
};
</script>
// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();
<!-- 發送事件的組件 -->
<script>
import { EventBus } from './event-bus.js';
export default {
methods: {
sendEvent() {
EventBus.$emit('my-event', 'Hello from event sender');
}
}
};
</script>
<!-- 監聽事件的組件 -->
<script>
import { EventBus } from './event-bus.js';
export default {
created() {
EventBus.$on('my-event', this.handleEvent);
},
beforeDestroy() {
EventBus.$off('my-event', this.handleEvent);
},
methods: {
handleEvent(data) {
console.log(data); // 'Hello from event sender'
}
}
};
</script>
選擇哪種通信方式取決于你的應用結構和個人偏好。對于簡單的父子通信,props和emit通常就足夠了。對于更復雜的應用,Vuex或provide/inject可能更合適。