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>
相关推荐
林涧泣8 小时前
【Uniapp-Vue3】开发userStore用户所需的相关操作
前端·vue.js·uni-app
css趣多多12 小时前
使用git管理uniapp项目
uni-app
前端小雪的博客.1 天前
Uniapp 小程序复制、粘贴功能实现
小程序·uni-app
竣子好逑1 天前
uniapp v2 组件
前端·uni-app
筱歌儿1 天前
uniapp 阿里云点播 播放bug
uni-app·bug
陆康永1 天前
uniapp-X 对象动态取值
uni-app
林涧泣1 天前
【Uniapp-Vue3】登录成功后获取当前用户信息并渲染到页面中
前端·javascript·uni-app
前端小雪的博客.1 天前
Uniapp 小程序接口封装与使用
微信小程序·uni-app
离别又见离别1 天前
uniapp 本地数据库多端适配实例(根据运行环境自动选择适配器)
数据库·vue.js·sqlite·uni-app·db
香菜的开发日记1 天前
uniapp 系统学习,从入门到实战(四)—— 页面与路由管理
uni-app