Vue: 兄弟组件利用自定义Bus传参


vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import * as path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(path.resolve(), 'src')
    }
  }
})

import * as Console from 'console'


type BusClass = {
  emit: (name: string) => void,
  on: (name: string, callback: Function) => void
}

type CallbackName = string | number | symbol

type List = {
  [key: CallbackName]: Array
}

class Bus implements BusClass {
  list: List

  constructor() {
    this.list = {}
  }

  emit(name: string, ...args: Array) {
    let callbacks: Array | undefined = this.list[name]
    if (callbacks === undefined) {
      console.warn(`event "${name}" is not bound`)
      return
    }
    callbacks.forEach(callback => {
      console.log('emit', this)
      callback.apply(this, args)  // this 为 Bus.ts 导出的实例, on方法如果使用ArrowFunction, 则无法使用this
    })
  }

  on(name: string, callback: Function) {
    let callbacks: Array = this.list[name] || []
    callbacks.push(callback)
    this.list[name] = callbacks
  }
}

export default new Bus()

App.vue






A.vue



B.vue



 

vue