Bus.ts
type BusClass = {
emit: (name: string) => void
on: (name: string, callback: Function) => void
}
type BusParams = string | number | symbol
type List = {
[key: BusParams]: Array<Function>
}
class Bus implements BusClass {
list: List
constructor() {
this.list = {}
}
emit(name: string, ...args: Array<any>) {
let eventName: Array<Function> = this.list[name]
eventName.forEach(ev => {
ev.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()
使用a组件
<template>
<h1>A.vue</h1>
<hr />
<button @click="change">传递</button>
<div class="box"></div>
</template>
<script lang="ts" setup>
import Bus from '../Bus'
let flag=true
const change=()=>{
flag=!flag
Bus.emit('son-click',flag)
}
</script>
<style>
.box {
width: 50px;
height: 50px;
border: 1px solid red;
}
</style>
b组件
<template>
<h1>B.vue</h1>
<hr />
<div class="box">{{flag}}</div>
</template>
<script lang="ts" setup>
import Bus from '../Bus'
import {ref} from 'vue'
let flag =ref(true)
Bus.on("son-click",(value:boolean)=>{
flag.value = value
})
</script>
<style>
.box {
width: 50px;
height: 50px;
border: 1px solid red;
}
</style>