跨组件通信是在开发过程中经常使用的,在 Vue3 中,官方推荐使用 Mitt 组件来进行通信。
npm install mitt --save
本文借鉴了https://www.cnblogs.com/CoderMonkie/p/use-eventhub-in-vue3.html
注册使用
在工具目录下创建一个eventHub.js
import Mitt from "mitt";
const eventHub = new Mitt();
export default eventHub;
将eventHub
注册到 Vue 实例(main.js
)
import { createApp } from "vue";
import App from "./App.vue";
import eventHub from "./utils/eventHub";
const app = createApp(App);
app.config.globalProperties.eventHub = eventHub;
app.mount("#app");
组件 1:发布事件
import eventHub from "../utils/eventHub";
import { getCurrentInstance, onMounted } from "vue";
export default {
name: "mine",
setup() {
const { eventHub } = getCurrentInstance().proxy;
onMounted(() => {
eventHub.emit("userLogout", "Hello"); //加入时发布一条消息
});
},
methods: {
logout() {
//一个点击事件,点击后发布消息。
sessionStorage.clear();
eventHub.emit("userLogout", "reload");
},
},
};
组件 2:监听事件
import { getCurrentInstance, onMounted } from "vue";
export default {
name: "headers",
setup() {
const eventHandler = async (params) => {
console.log(params); //收到消息后输出到控制台
};
const { eventHub } = getCurrentInstance().proxy;
eventHub.on("userLogout", eventHandler);
onBeforeUnmount(() => {
eventHub.off("userLogout", eventHandler);
});
},
};