vue3中总线事件的应用(组件间事件传递)

        在两个组件关系比较复杂,在使用emit传递事件比较麻烦的情况下,可以使用总线bus来传递事件,具体实现如下:

1.引入插件mitt

npm install mitt --save

2.创建一个bus.js,放在你的方法文件中

import mitt from 'mitt'
export const bus= mitt()

3.在触发事件的组件中使用

import { bus} from '../../../utils/bus' 
const emitChangeHistory =()=>{
        bus.emit('changeHistory')
}

const save=()=>{
    ...
     emitChangeHistory() // 触发
}

4.在监控事件的组件中使用

import { bus } from '../utils/bus' 
onMounted(()=>{
  bus.on('changeHistory',()=>{
     // 更新历史版本
     getHistories()
    })
  })
onBeforeUnmount(()=>{
  bus.off('changeHistory')
})

        通过以上步骤,就比较容易的实现事件的传递了,尤其在组件的嵌套关系比较复杂时,应用就及其方便了。

你可能感兴趣的:(vue.js,前端,javascript)