- type BusClass = {
- emit: (name: string) => void
- on: (name: string, cab: 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, cab: Function) {
- let fn: Array<Function> = this.list[name] || [];
- fn.push(cab)
- this.list[name] = fn
- }
- }
-
- export default new Bus()
使用
- <script lang="ts" setup>
- import { ref } from 'vue'
- import Bus from '../Bus';
- Bus.emit('changeName', '请修改数据')
- const title = ref('这是A组件')
- Bus.on('changeName', (name: string)=>{
- title.value = name
- })
- </script>