uni-app实现页面通信EventChannel

uni-app实现页面通信EventChannel

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

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

// index.vue
<script setup>
	uni.navigateTo({
		url: '/pages/tender/detail', // 跳转详情页面
	    success:function(res){
	      // 通过eventChannel向被打开页面传送数据
	      res.eventChannel.emit('toDetailEmits', { data: 'index to detail' })
	    }
	});
</script>
// 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. 如果需要获取被打开页面传送到当前页面的数据

// 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>
// 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. uni-app页面通讯的基本使用

    2024-06-06 17:22:06       49 阅读
  2. uni-app中,实现页面之间传参

    2024-06-06 17:22:06       36 阅读
  3. 通过 Vue 3 组合式 API 优化 Uni-app 基础页面功能

    2024-06-06 17:22:06       103 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-06 17:22:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-06 17:22:06       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-06 17:22:06       82 阅读
  4. Python语言-面向对象

    2024-06-06 17:22:06       91 阅读

热门阅读

  1. Android串口调试ADB

    2024-06-06 17:22:06       28 阅读
  2. 元宇宙概念及关键技术

    2024-06-06 17:22:06       32 阅读
  3. 调用大模型API 给产业分类

    2024-06-06 17:22:06       34 阅读
  4. 什么情况下AI可以不用预先设定算法和规则?

    2024-06-06 17:22:06       31 阅读
  5. matlab误差估计扩展卡尔

    2024-06-06 17:22:06       28 阅读
  6. 优化耗时业务:异步线程在微服务中的应用

    2024-06-06 17:22:06       33 阅读
  7. Pytorch 叶子节点和非叶子节点的理解

    2024-06-06 17:22:06       27 阅读