uniapp 页面通信

navigateTo

js 复制代码
// 在起始页面跳转到test.vue页面,并监听test.vue发送过来的事件数据
uni.navigateTo({
  url: '/pages/test?id=1',
  events: {
    // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
    acceptDataFromOpenedPage: function(data) {
      console.log(data)
    },
    ...
  },
  success: function(res) {
    // 通过eventChannel向被打开页面传送数据
    res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'data from starter page' })
  }
})

注意:vue3 与 vue 2 被打开页面初始化 略有不同

vue2

js 复制代码
onLoad: function(option) {
  const eventChannel = this.getOpenerEventChannel();
  // 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
  eventChannel.on('acceptDataFromOpenerPage', function(data) {
    console.log(data)
  })
}

Vue3

js 复制代码
// 在test.vue页面,向起始页通过事件传递数据
import { onLoad } from '@dcloudio/uni-app'
import { getCurrentInstance, ref } from 'vue'
const _this = getCurrentInstance().proxy
onLoad(() => {
  let eventChannel = _this.getOpenerEventChannel()
  // 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
  eventChannel.on('acceptDataFromOpenerPage', (data) => {
  	console.log(data)
  })
})

被打开页面,向打开页面传递消息,需要将 eventChannel 缓存,并在对应时刻,调用 eventChannel.emit

js 复制代码
<script setup>
let eventChannel = null

onLoad(() => {
  // xxx
  eventChannel = _this.getOpenerEventChannel()
})
const submit = () => {
  eventChannel.emit('onConfirm', {})
  uni.navigateBack()
}
</script>
相关推荐
崔庆才丨静觅6 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60617 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅7 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅7 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅7 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅8 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊8 小时前
jwt介绍
前端
爱敲代码的小鱼8 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax