1.新建一个vueBus.js
// vusBus.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;
2.在main.js注册使用
// main.js
import VueBus from "./libs/vueBus.js";
...
Vue.use(VueBus);
3.在任意组件中使用
// nav.vue
this.$bus.$emit("do-search", this.keyword);
...
// main.vue
created() {
this.$bus.$on("do-search", (keyword) => {
....func...//处理方法
})
}
beforeDestroy() {
this.$bus.$off("do-search") // 关闭事件
}