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>
相关推荐
吴传逞1 天前
记一次uniapp微信小程序开发scss变量失效的问题
微信小程序·uni-app·scss
2501_915921431 天前
小团队如何高效完成 uni-app iOS 上架,从分工到工具组合的实战经验
android·ios·小程序·uni-app·cocoa·iphone·webview
2501_916008891 天前
uni-app iOS 文件管理与 itools 配合实战,多工具协作的完整流程
android·ios·小程序·https·uni-app·iphone·webview
!win !1 天前
uni-app项目Tabbar实现切换icon动效
小程序·uni-app
xw51 天前
uni-app项目Tabbar实现切换icon动效
前端·uni-app
2501_916007471 天前
uni-app iOS 文件调试常见问题与解决方案:结合 itools、克魔、iMazing 的实战经验
android·ios·小程序·https·uni-app·iphone·webview
豆豆(设计前端)1 天前
使用 Uni-app 打包 外链地址APK 及 iOS 注意事项
ios·uni-app
jingling5551 天前
uniapp | 解决组件样式不生效问题
前端·css·uni-app·html·学习方法
^Rocky1 天前
微信小程序(uniapp)实现连接蓝牙
微信小程序·uni-app·蓝牙连接
2501_915918412 天前
uni-app 项目 iOS 上架踩坑经验总结 从证书到审核的避坑指南
android·ios·小程序·https·uni-app·iphone·webview