我的代码使用了
this.$router
.replace({
path: '/searchList',
query: {
},
})
.catch((err) => {
if (err.name !== 'NavigationDuplicated') {
console.error(err);
}
});
这种页面跳转方式,这种方式会导致页面不会被销毁(这样跳转加上逻辑之后可以保持页面没有刷新的白屏)
下面的eventbus是增强过的,只会保留一个最新的实例
- 实例代码
/**
* 保持一个最新的
* 因为使用页面不刷新的方式执行页面跳转的情况会导致eventbus重复调用(没法执行组件重载),所以在每次跳转的时只加载一个最新的eventbus的组件
* this.$router
.replace({
path: '/searchList',
query: {
},
})
.catch((err) => {
if (err.name !== 'NavigationDuplicated') {
console.error(err);
}
});
*/
import Vue from 'vue';
const rawBus = new Vue();
const activeListeners = new Map(); // 存储当前活动的监听器
const eventBus = {
$on(event, callback) {
// 移除该事件之前的所有监听器
this.$off(event);
// 包装回调以统一管理
const wrappedCallback = (...args) => {
if (process.env.NODE_ENV === 'development') {
console.debug(`[EventBus] ${event} 被触发`, { payload: args });
}
callback.apply(this, args);
};
// 注册新监听器并记录
rawBus.$on(event, wrappedCallback);
activeListeners.set(event, wrappedCallback);
return this;
},
$off(event) {
if (activeListeners.has(event)) {
// 移除监听器并清理记录
rawBus.$off(event, activeListeners.get(event));
activeListeners.delete(event);
}
return this;
},
$emit: rawBus.$emit.bind(rawBus),
$once: rawBus.$once.bind(rawBus),
};
// 开发环境监控
if (process.env.NODE_ENV === 'development') {
setInterval(() => {
console.groupCollapsed('[EventBus 状态监控]');
activeListeners.forEach((_, event) => {
console.log(`%c${event}`, 'color: #409EFF', '→ 监听器: 1 (最新)');
});
console.groupEnd();
}, 10000);
}
export default eventBus;
/**
*
1utils工具类 命名bus.js 最好放在components或者utils目录下
import Vue from "vue";
const bus = new Vue();
export default bus;
2加入到mian方法中(我用的是vue2)
import eventBus from '@/utils/eventBus';
Vue.prototype.$eventBus = eventBus;
3使用方法
//发消息
let _this = this;
_this.$bus.$emit("areaChangs", [参数1, 数据2]);
//收消息
let _this = this;
this.$bus.$on("areaChangs", function(data) {
//这个是匿名函数哦,不饿能直接用this
_this.data= data;
});
*/
- 加入到mian方法中(我用的是vue2)
import Bus from "./utils/bus";
Vue.prototype.$bus = Bus;
- 调用方法
//发消息
let _this = this;
_this.$bus.$emit("areaChangs", [参数1, 数据2]);
//收消息
let _this = this;
this.$bus.$on("areaChangs", function(data) {
//这个是匿名函数哦,不饿能直接用this
_this.data= data;
});