zoukankan      html  css  js  c++  java
  • Vue封装中央事件总线插件vue-bus

    1.第一步:新建vue-bus文件夹,在该文件下新建index.js

    /*
    封装一个中央事件总插件vue-bus,可以在任意组件间使用,而不需要导入bus
    给Vue添加一个属性$bus,并代理$emit, $on, $off三个方法
    */

     1 const install = function(Vue) {
     2     const Bus = new Vue({
     3         methods: {
     4             emit (event, ...args) {
     5                 this.$emit(event, ...args);
     6             },
     7             on (event, callback) {
     8                 this.$on(event, callback);
     9             },
    10             off (event, callback) {
    11                 this.$off(event, callback);
    12             },
    13         }
    14     })
    15 
    16     Vue.prototype.$bus = Bus;
    17 }
    18 
    19 export default install;

    2.第二步:

    在main.js中使用:

    import VueBus from './vue-bus';
    Vue.use(VueBus);

    3.第三步就可以在组件中使用了:

     1 backtoHome() {
     2         this.$bus.emit('overfl-visi',this.overflVisible);
     3         this.$router.push('/home');
     4     }
     5     
     6 
     7 created () {
     8             this.$bus.on('overfl-visi', this.changeOverflow);
     9 }
    10 
    11 beforeDestroy () {
    12             this.$bus.off('overfl-visi', this.changeOverflow);    
    13         }

    使用vue-bus有两点需要注意:

    第一是$bus.on应该再created钩子内使用,如果在mounted使用,它可能接收不到其他组件来自created钩子内发出的事件
    第二是使用了$bus.on,在beforeDestroy钩子里应该使用$bus.off解除。因为组件销毁后,就没必要把监听的句柄储存在vue-bus里了。

  • 相关阅读:
    Centos6.8下设置gitlab服务开机自启动,关闭防火墙开机自启动
    gitlab设置SSH key
    在centos6.8下安装gitlab遇到的坑
    recyclerView中的方法
    ListView中的方法
    tcp断开时分几步
    get,post区别
    cookie是什么,在什么地方会用到
    http和https的区别
    keystore是个嘛东西
  • 原文地址:https://www.cnblogs.com/tian-long/p/8418450.html
Copyright © 2011-2022 走看看