Vue-bus中央事件总线插件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_17775997/article/details/82900302

编辑文章

这个插件可以在可以在所有的组件之间随意使用

const install = function (Vue) {
    const Bus = new Vue({
        methods: {
            emit (event, ...args) {
                this.$emit(event, ...args);
            },
            on (event, callback) {
                this.$on(event, callback);
            },
            off (event, callback) {
                this.$off(event, callback);
            }
        }
    });
    Vue.prototype.$bus = Bus;
};

export default install;
  • 在main.js中使用插件:
import VueBus from './vue-bus' ;
Vue.use(VueBus);
  • 使用vue-bus有两点需要注意,第一是 $bus.on应该在 created钩子内使用,如果在mounted使用,它可能接受不到其他组件来自created钩子发出的事件;第二点是使用了$bus.on,在beforeDestroy钩子里应该使用$bus.off解除,因为组件销毁后,就没必要把监听的句柄储存在vue-bus里了。
created() {
    this.$bus.on('add',this.addfunction);
}

beforedestroy() {
  this.$$bus.off('add',this.addfunction);
}

猜你喜欢

转载自blog.csdn.net/sinat_17775997/article/details/82900302