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>
相关推荐
夏幻灵10 分钟前
HTML5里最常用的十大标签
前端·html·html5
Mr Xu_24 分钟前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
未来龙皇小蓝27 分钟前
RBAC前端架构-01:项目初始化
前端·架构
程序员agions36 分钟前
2026年,微前端终于“死“了
前端·状态模式
万岳科技系统开发36 分钟前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
2501_9151063238 分钟前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
程序员猫哥_43 分钟前
HTML 生成网页工具推荐:从手写代码到 AI 自动生成网页的进化路径
前端·人工智能·html
龙飞0544 分钟前
Systemd -systemctl - journalctl 速查表:服务管理 + 日志排障
linux·运维·前端·chrome·systemctl·journalctl
2501_915106321 小时前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
我爱加班、、1 小时前
Websocket能携带token过去后端吗
前端·后端·websocket