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>
相关推荐
iOS阿玮6 小时前
1V1 社交精准收割 3.6 亿!40 款马甲包 + 国内社交难度堪比史诗级!
uni-app·app·apple
脾气有点小暴10 小时前
uniapp开发APP 内嵌外部 HTTPS 链接的实现方案
vue.js·uni-app
硕子鸽18 小时前
UniApp + Dify 实战:详解 SSE 流式响应的解析与前端渲染
前端·uni-app·dify
2501_9159184118 小时前
iOS 项目中证书管理常见的协作问题
android·ios·小程序·https·uni-app·iphone·webview
Miketutu18 小时前
[特殊字符] uni-app App 端实现文件上传功能(基于 xe-upload 插件)
前端·vue.js·uni-app
焚 城18 小时前
uniapp 各种文件预览实现
vue.js·uni-app·html
weixin79893765432...18 小时前
uni-app 全面深入的解读
uni-app
2501_9159184118 小时前
提升 iOS 应用安全审核通过率的一种思路,把容易被拒的点先处理
android·安全·ios·小程序·uni-app·iphone·webview
00后程序员张18 小时前
APP如何快速上架Apple Store:完整上架流程与常见问题解析
android·小程序·https·uni-app·iphone·webview
ifeng091818 小时前
uniapp开发鸿蒙:跨端兼容与条件编译实战
华为·uni-app·harmonyos