以下是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: List
constructor() {
this.list = {}
}
emit(name: string, ...args: Array<any>) {
let eventName: Array<Function> = this.list[name]
eventName.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()
兄弟组件A组件代码
***使用Bus.emit传值***
<template>
<div class="a_main">
我是A组件
<button @click="changeEmit">修改值</button>
</div>
</template>
<script lang='ts' setup>
import { defineEmits, ref } from 'vue'
import Bus from '../Bus'
let flag = false;
const changeEmit = () => {
flag = !flag
Bus.emit('on-click', flag)
}
</script>
<style scoped lang="scss">
.a_main {
width: 100%;
height: 200px;
background: red;
color: #fff;
}
</style>
兄弟组件B组件代码
使用Bus.on接收值
<template>
<div class="b_main">
我是B组件{{ Flag }}
</div>
</template>
<script lang='ts' setup>
import Bus from '../Bus'
import { ref } from 'vue'
let Flag = ref(false)
Bus.on('on-click', (flag: boolean) => {
console.log(flag)
Flag.value = flag
})
</script>
<style scoped lang="scss">
.b_main {
width: 300px;
height: 300px;
background: blue;
}
</style>
如果我们不想使用这个,想使用更多功能的内置的写好的组件请点击下方链接,教你使用Mitt,vue3的EventBus
mitt用法