Vue3 全局事件总线 Vue.prototype.$bus = this , $on $emit $off 绑定与使用

原因:

        由于Vue3中的mian.js文件中,已经不提供Vue2的挂载方式,  Vue.prototype.$bus = this 

        Vue2:

new Vue({
  el:'#app',
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this // 安装全局事件总线
  }
})

        Vue3:


createApp(App).mount('#app')

       

解决:

        需要使用第三方库  EventBus

        

安装

$ npm install --save vue3-eventbus
   

挂载

import eventBus from 'vue3-eventbus'
    app.use(eventBus)
   

使用

// Button.vue
import bus from 'vue3-eventbus'
export default {
    setup() {
        bus.emit('foo', { a: 'b' })
    }
}

引入后:

       main.js中使用 use() 方法

import eventBus from 'vue3-eventbus'


createApp(App).use(eventBus).mount('#app')

        其它文件引入后,,

                使用  bus.on()  替代  原本  this.$bus.$on()  写法

                以此类推   bus.emit()、 bus.off()、 bus.on()

        

import bus from 'vue3-eventbus'

mounted(){

    //Vue2
    this.$bus.$on()
    

   //现在
   bus.on()

}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值