uni-app实现页面通信EventChannel

uni-app实现页面通信EventChannel

之前使用了EventBus的方法实现不同页面组件之间的一个通信,在uni-app中,我们也可以使用uni-app API ------ uni.navigateTo来实现页面间的通信。注:2.8.9+ 支持页面间事件通信通道。

1. 向被打开页面传送数据

javascript 复制代码
// index.vue
<script setup>
	uni.navigateTo({
		url: '/pages/tender/detail', // 跳转详情页面
	    success:function(res){
	      // 通过eventChannel向被打开页面传送数据
	      res.eventChannel.emit('toDetailEmits', { data: 'index to detail' })
	    }
	});
</script>
javascript 复制代码
// detail.vue
import { onLoad } from '@dcloudio/uni-app';
import { ref, getCurrentInstance} from 'vue';
const instance = getCurrentInstance().proxy

<script setup>
	onLoad(()=>{
		const eventChannel = instance.getOpenerEventChannel();
		eventChannel.on('toDetailEmits',(data)=>{
		  console.log(data,'data') // 输出结果如下
		})
	})
</script>

2. 如果需要获取被打开页面传送到当前页面的数据

javascript 复制代码
// index.vue
<script setup>
	uni.navigateTo({
		url: '/pages/tender/detail', // 跳转详情页面
	    events:{
	      // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
	      updataEmits:function(data){
	        console.log(data,'data index')  // 输出结果如下
	        // 可以在当前页做一些操作....
	      }
	    },
	    success:function(res){
	      // 通过eventChannel向被打开页面传送数据
	      res.eventChannel.emit('toDetailEmits', { data: 'index to detail' })
	    }
	});
</script>
javascript 复制代码
// detail.vue
import { onLoad } from '@dcloudio/uni-app';
import { ref, getCurrentInstance} from 'vue';
const instance = getCurrentInstance().proxy

<script setup>
	// 如点击某一按钮
	const cancle = () => {
		const eventChannel = instance.getOpenerEventChannel();
	    eventChannel.emit('updataEmits',{data:'detail to index'})
	    uni.navigateBack()
	}

	onLoad(()=>{
		const eventChannel = instance.getOpenerEventChannel();
		eventChannel.on('toDetailEmits',(data)=>{
		  console.log(data,'data') 
		})
	})
</script>
相关推荐
以对_5 小时前
uview表单校验不生效问题
前端·uni-app
小雨cc5566ru16 小时前
uniapp+Android面向网络学习的时间管理工具软件 微信小程序
android·微信小程序·uni-app
二十雨辰21 小时前
[uni-app]小兔鲜-04推荐+分类+详情
前端·javascript·uni-app
小雨cc5566ru1 天前
hbuilderx+uniapp+Android健身房管理系统 微信小程序z488g
android·微信小程序·uni-app
敲啊敲95271 天前
uni-app之旅-day02-分类页面
前端·javascript·uni-app
二十雨辰1 天前
[uni-app]小兔鲜-06地址+sku+购物车
前端·javascript·vue.js·uni-app
康康爹1 天前
uniapp 小程序,登录上传头像昵称页面处理步骤
小程序·uni-app
小雨cc5566ru1 天前
微信小程序hbuilderx+uniapp+Android 新农村综合风貌旅游展示平台
android·微信小程序·uni-app
小雨cc5566ru1 天前
小程序 uniapp+Android+hbuilderx体育场地预约管理系统的设计与实现
android·小程序·uni-app
某公司摸鱼前端2 天前
uniapp 上了原生的 echarts 图表插件了 兼容性还行
前端·uni-app·echarts