vue3兄弟组件传参bus

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>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容