当前位置: 首页 > Web前端 > vue.js

Vue-EventBus

时间:2023-03-31 17:09:52 vue.js

定义了一个全局定义,可以将eventBus绑定到vue实例的原型上,也可以直接绑定到window对象上。//main.js(可以用任何JS写)//方法1Vue.prototype.$EventBus=newVue();//在mian中,方法1可以这样写newVue({router,render:h=>h(App),beforeCreated(){Vue.prototype.$EventBus=this}}).$mount('#app')//方法2window.eventBus=newVue();触发事件//使用方法一定义时this.$EventBus.$emit('eventName',param1,param2,...)//使用方法二定义时,EventBus.$emit('eventName',param1,param2,...)监听事件//使用第一个方法定义时this.$EventBus.$on('eventName',(param1,param2,...)=>{//要执行的代码})//当使用第二种方法定义EventBus.$on('eventName',(param1,param2,...)=>{//需要执行的代码})移除事件监听器为了避免监听时事件被反复触发,通常需要在页面销毁时移除事件监听器。或者在开发过程中,由于热更新,可能会多次绑定监听事件,此时需要去掉事件监听。//this.$EventBus.$off('eventName')当使用方法一定义时;//使用方法二定义时EventBus.$off('eventName');