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()
App.vue
<template> <div> <A></A> <B></B> </div> </template> <script setup lang="ts"> import A from './components/Bus/A.vue' import B from './components/Bus/B.vue' </script> <style scoped></style>
A.vue
<template> <div class="A"> <h1>我是A组件</h1> <el-button @click="emitB">派发一个事件</el-button> </div> </template> <script setup lang="ts"> import Bus from '../../Bus' let flag = false const emitB = () => { flag = !flag Bus.emit('on-click', flag) } </script> <style scoped> .A { width: 400px; height: 400px; background: orange; } </style>
B.vue
<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 }) </script> <style scoped> .B { width: 400px; height: 400px; background: rgb(19, 138, 15); } </style>
兄弟组件传值还有一个插件:MITT
npm install mitt -S