父级:
<template><div><!-- <A @on-click="getFlag"></A><B :flag="Flag"></B> --><A></A><B></B></div>
</template><script setup lang="ts">
import { ref } from "vue";
import A from "./components/A.vue";
import B from "./components/B.vue";
// const Flag = ref(false);
// const getFlag = (params: boolean) => {
// Flag.value = params;
// };
</script><style></style>
A组件:
<template><div class="A"><button @click="emitB">派发一个事件</button></div>
</template><script setup lang="ts">
// const emit = defineEmits(["on-click"]);
import Bus from '../bus';let flag = false;
const emitB = () => {flag = !flag;// emit("on-click", flag);Bus.emit('on-click',flag);
};</script><style>
.A{width: 200px;height: 200px;color: #fff;background: blue;
}
</style>
B组件:
<template><div class="B"><h1>B组件</h1>{{Flag}}</div>
</template><script setup lang='ts'>
import Bus from "../Bus";
import {ref} from "vue";
let Flag=ref(false);
Bus.on('on-click',(flag:boolean)=>{Flag.value=flag;
})// type Props={// flag:boolean// }// defineProps<Props>();</script><style>.B{width:200px;height: 200px;color:#fff;background: red;}
</style>
Bus.ts:
type BusClass = {emit: (name:string) => void,on:(name:string,callback:Function)=>void
}type Pramskey = string | number | symbol;type List = {[key:Pramskey]:Array<Function>
}class Bus implements BusClass{list: Listconstructor() {this.list={}}emit(name: string,...args:Array<any>) {let evenentName:Array<Function> = this.list[name];evenentName.forEach(fn => {fn.apply(this,args)})}on(name:string,callback:Function) {let fn:Array<Function> = this.list[name] || [];fn.push(callback);this.list[name] = fn;}}export default new Bus();
效果图: