1.event-bus.js vue插件
//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; //将bus挂载到全局的vue实例上
return Bus;
};
export default install;
2.main.js
import Vue from 'vue'
import App from './App'
import Bus from './util/event-bus';
let vConsole = new VConsole()
Vue.use(Bus);
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
components: {App},
template: '<App/>'
});
3.在router/index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
//必须实例化 Vue,插件安装在vue实例上,所以必须实例化
let vm = new Vue();
const router = new Router({
mode: 'history',
routes: [ ]
})
router.beforeEach((to, from, next) => {
vm.$bus.emit('hello');
next()
})
export default router
网友评论