下载地址
一、传入的监听函数名是自定义的,关于重载、报错问题
参考连接:
https://blog.youkuaiyun.com/ThisEqualThis/article/details/128478261
二、基础使用问题参考官网
三、关于组件间传值问题
举例1:A,B组件都已经挂载,A种触发emit,B种监听。是触发完成之后,先执行监听再执行A种后续代码
<template>
<div class="home_view">
<B />
</div>
</template>
<script setup lang="ts">
import { onMounted, nextTick } from "vue";
import mitt from "@/util/bus";
import B from "@/components/head/ViewTitle.vue";
nextTick(() => {
mitt.emit("changeTitle", "hello");
console.log("是否先执行");
});
</script>
<template>
<div class="home_view">
<div class="box1"></div>
</div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted } from "vue";
import mitt from "@/util/bus";
onMounted(() => {
// 监听事件
mitt.on("changeTitle", changeTitle);
});
function changeTitle(title: string) {
document.title = title;
console.log("标题已更改为:", title);
}
onUnmounted(() => {
// 清除事件监听
mitt.off("changeTitle");
});
</script>
<style lang="scss" scoped>
.box1 {
width: 300px;
height: 300px;
border: 1px solid red;
margin-top: 20px;
}
执行结果:
标题已更改为: hello
是否先执行
举例2:A页面先挂载,然后触发emit,此时B页面还没有挂载,A触发之后,跳转B页面,是监听不到值的变化
1.mitt 的事件总线是瞬时的 - 当事件被触发时,只有当前已经注册的监听器能接收到该事件
2.生命周期不同步,A 页面触发事件时,B 页面尚未挂载,因此没有注册监听器
3.事件不会持久化 - mitt 不会存储已触发的事件
解决方案
1.延迟触发时间,可以在路由跳转的时候进行触发
const handleClick = () => {
router.push("/b").then(() => {
mitt.emit("changeTitle", "hello");
console.log("是否先执行");
});
};
2.如果持久化事件状态,个人观点,从代码可读性,以及处理问题方案来看,不是最优解
3.更换数据交互方式,例如pinia,或者路由传参等