vue 使用 eventBus

文件 vue-bus.js

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);

其他地方就可以使用了,使用方式如下:

this.$bus.$emit

this.$bus.$on   一般在created阶段

this.$bus.$off   一般在beforeDestroy阶段

猜你喜欢

转载自blog.csdn.net/u010238381/article/details/81100538