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>
相关推荐
想要飞翔的pig4 分钟前
uniapp+vue3页面滚动加载数据
前端·vue.js·uni-app
会功夫的李白16 分钟前
uniapp自动构建pages.json的vite插件
前端·uni-app·vite
TE-茶叶蛋1 小时前
Uniapp、Flutter 和 React Native 全面对比
flutter·react native·uni-app
特立独行的猫a4 小时前
uni-app 开发HarmonyOS的鸿蒙影视项目分享:从实战案例到开源后台
uni-app·开源·harmonyos·鸿蒙·影视
七七小报7 小时前
uniapp-商城-61-后台 新增商品(添加商品到数据库)
uni-app
hbcui19847 小时前
uni-app x正式支持鸿蒙原生应用开发
uni-app·harmonyos·uni-app x
lqj_本人7 小时前
鸿蒙OS&UniApp制作支持多图上传的图片选择器:打造高性能移动端上传体验#三方框架 #Uniapp
华为·uni-app·harmonyos
好好的哦9 小时前
uni-app小程序登录后…
小程序·uni-app
!win !1 天前
uni-app小程序登录后…
前端·uni-app
aklry1 天前
uniapp实现在线pdf预览以及下载
前端·pdf·uni-app