uniapp使用EventBus实现页面间数据传递

前情

最近在做小程序项目,选用是当前比较火的uniapp技术栈,经常会遇到页面间消息传递的需求。

为什么要这么做?

uniapp页面间数据通信方式有很多:通过url传参,状态管理库vuex/pinia,本地存储,事件通道eventChannel,EventBus等,

这次的需求是在A面点击一个按钮跳转到B页面拾取一个数据选项再返回A页面用B页面拾取的数据做接下来逻辑处理,像这种情况用事件通道和EventBus来做是比较好的,EventBus相对使用更简单一些,所以使用EventBus

实现代码

A页面

<template>
  <view>
    <text>我是A页面</text>
	  <button @click="gotoPageB">点我去B页面</button>
  </view>
</template>

<script>
export default {
  mounted() {
	  this.handleCustomEventBind = this.handleCustomEvent.bind(this);
    uni.$on('customEvent', this.handleCustomEventBind);
  },
  destory() {
	  uni.$off('customEvent', this.handleCustomEventBind);
  },
  methods: {
	  gotoPageB() {
		  uni.redirectTo({
				url: '/pages/pageB/pageB'
			});
	  },
    handleCustomEvent(event) {
	    console.log(event.data); // 输出: Hello from Component B
      // 处理事件的业务逻辑
      // ...
    }
  }
};
</script>

B页面

<template>
  <view>
	  <text>我是B页面</text>
    <button @tap="triggerEvent">点我</button>
  </view>
</template>

<script>
export default {
  methods: {
    triggerEvent() {
      uni.$emit('customEvent', { data: 'Hello from Component B' });
      uni.navigateBack();
    }
  }
};
</script>

注意

因为这种事件监听是全局的,所以在定义事件名的最好是是保证唯一,除非确实有多个地方要用到,而且最好是在页面销毁的时候记得清除不需要的事件监听。

posted @ 2024-05-31 19:51  !win !  阅读(72)  评论(0编辑  收藏  举报