EventEmitter

178 阅读1分钟

event传递事件

www.runoob.com/nodejs/node…

在组件传递事件事使用。比如用在弹窗里。

举例如

1.打开文件events.js文件,导出一个名字,一个唯一的常量。

export const SHOW_ADD_REPORT_MANAGER="SHOW_ADD_REPORT_MANAGER"

2.在一个文件里,这个文件是父文件如inde.vue,有一个新增的按钮 ,点击这个按钮出现一个弹窗

这个弹窗是另一个组件

如src/components/AddReportManager.vue

在父文件里引入这个弹窗组件,注册组件

import AddReportManage from "@/components/AddReportManager.vue"
components{
AddReportManage
}

使用组件

<Div>
<AddReportManage/>
</Div>

引入events.js

import *as events from "@/events.js"

编写点击新增的函数

showAddwin()=>{
events.emitter.emit(events.SHOW_ADD_REPORT_MANAGER,{
mode:"add"
})
}

events.emitter.emit(events.SHOW_ADD_REPORT_MANAGER,{}))}的意思是唤醒打开弹窗,可以唤醒的条件是你必须在弹窗组件中监听了events事件,

在弹窗组件里引入

improt *as events from "@/components/events.js"
mounted(){
events.emitter.on(events.SHOW_ADD_REPORT_MANAGER,this.showAddwin)
},
//组件销毁后这个监听也要取消掉
beforeDestroy(){
events.emitter.removeAllListeners(events.SHOW_ADD_REPORT_MANAGER)
}

表示:在组件被挂载到页面时,就一直监听着 events 事件,在组件销毁之前,将监听事件取消掉。