在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可能更合适。