作用
和vue一样,用于跨级/非跨级组件通讯,也是组件通讯常用的一种方式。
用法
- 下载包hy-event-store
- 创建实例
- 组件1抛出事件:
emit('eventName', args)
- 组件2 componentDidMount中接受事件:
on('eventName',(args)=>{doSomthing()})
- 组件2 componentWillUnmount销毁事件:
off('eventName',doSomthing})
step1:下载包hy-event-store
npm i hy-event-store
step2:创建eventBus实例,一般放在独立的文件中,并导出【因为emit和on组件都要引入】
import { HYEventBus } from 'hy-event-store'
const eventBus = new HYEventBus()
export default eventBus
step3:组件1抛出事件,携带参数
import eventBus from '../utils/event-bus'
clickNext () {
console.log('next')
eventBus.emit('subNext', { name: 'guoguo', date: '8-30' })
}
step4: 组件2在DOM加载生命周期中接受事件,直接调用组件的中的一个提前声明的回调函数,这样注销事件,只需要传入该函数即可
import eventBus from './utils/event-bus'
eventBus.on('subNext', (value) => this.subNext(value))
subNext (val) {
console.log('app监听到了孙节点', val)
}
step5: 组件2在卸载生命周期中,销毁事件监听
componentWillUnmount () {
eventBus.off('subPre', this.subPreClick)
eventBus.off('subNext', this.subNext)
}