vue中事件总线bus的用法

  • ./util/Bus.js

    import Bus from 'vue';
    let install = function (Vue) {
    	// 设置eventBus
    	Vue.prototype.bus = new Bus();
    }
    
    export default { install };
  • 安装: npm install vue-bus
  • 在main.js 中引入vuebus:
  • 1
    2
    3
    4
    import Vue from 'vue';
    import VueBus from 'vue-bus';
     
    Vue.use(VueBus);

     

    在组件中使用 

    触发事件:

    this.$bus.emit("事件名",值)
    应对事件:
    mounted:function(){
    this.$bus.on("事件名",function(值){

    });
    },
    destroyed:function(){
    this.$bus.off("事件名");
    }
     
     
    this.$bus.emit  ==>    触发
    this.$bus.on    ==>     接収
    this.$bus.off   ==>     清除
     
    注意:接收后要清除事件,不然会造成不必要的后果!!!
posted @ 2021-11-14 14:10  李李凯凯  阅读(284)  评论(0编辑  收藏  举报