eventbus前端父子组件通信使用及重复实例问题解决(保留最新的一个)如果出现bug请在评论指出,看到会改

我的代码使用了

this.$router
				.replace({
					path: '/searchList',
					query: {
					},
				})
				.catch((err) => {
					if (err.name !== 'NavigationDuplicated') {
						console.error(err);
					}
				});

这种页面跳转方式,这种方式会导致页面不会被销毁(这样跳转加上逻辑之后可以保持页面没有刷新的白屏)

下面的eventbus是增强过的,只会保留一个最新的实例

  1. 实例代码
/**
 * 保持一个最新的
 * 因为使用页面不刷新的方式执行页面跳转的情况会导致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;
    });
 */

  1. 加入到mian方法中(我用的是vue2)
import Bus from "./utils/bus";
Vue.prototype.$bus = Bus;
  1. 调用方法
//发消息
let _this = this;
_this.$bus.$emit("areaChangs", [参数1, 数据2]);
//收消息
let _this = this;
  this.$bus.$on("areaChangs", function(data) {
  //这个是匿名函数哦,不饿能直接用this
  _this.data= data;
  });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值