uniApp跨页面通讯$on、$emit、$once、$off使用场景及技巧

大部分场景实际上利用once、emit、$off配合使用即可,直接上代码

在页面B中,离开时必须要销毁$once(xxx),因为在B页面,点击拍照才会触发$emit(xxx),如果通过滑动或点击头部返回页面A,once(xxx)将会和下一次emit(xxx)调用时,一起触发。
所以调用销毁方法$off(xxx)的实际很重要,onUnmounted配合nextTick使用,刚好不会影响上个页面A正常通过takePhoto 触发的事件

页面A

javascript 复制代码
<template>
  <button @click="fn1">按钮1</button>
  <button @click="fn2">按钮2</button>
</template>

<script setup lang='ts'>
import { reactive, toRefs, onBeforeMount, onMounted } from 'vue'
const state = reactive({
  list1: [] as string[],
  list2: [] as string[]
})

const fn1 = () => {
  uni.navigateTo({ url: '页面B'})
  uni.$once('xxx', () => {
    // 监听后的逻辑
  })
}

const fn2 = () => {
  uni.navigateTo({ url: '页面B'})
  uni.$once('xxx', () => {
    // 监听后的逻辑
  })
}

</script>

<style lang="scss" scoped>

</style>

页面B

javascript 复制代码
<template>
  <my-header>点击可返回</my-header>
  <camera device-position="back" flash="off" style="width: 100%; height: 300px;"></camera>
  <button type="primary" @click="takePhoto">拍照</button>
</template>

<script setup lang='ts'>
import { reactive, toRefs, nextTick, onUnmounted } from 'vue'
const takePhoto = () => {
  const ctx = uni.createCameraContext();
  ctx.takePhoto({
    quality: 'high',
    success: (res) => {
      uni.$emit('xxx', res)
    }
  })
}

onUnmounted(() => {
  nextTick(() => {
    uni.$off('xxx')
    uni.navigateBack()
  })
})
</script>

<style lang="scss" scoped></style>
相关推荐
万物得其道者成15 小时前
UniApp 多端滑块验证码插件 zxj-slide-verify 实用指南
uni-app
蓝帆傲亦17 小时前
支付宝小程序性能暴增秘籍:UniApp项目极限优化全攻略
小程序·uni-app
2501_916008891 天前
深入解析iOS机审4.3原理与混淆实战方法
android·java·开发语言·ios·小程序·uni-app·iphone
QT.qtqtqtqtqt1 天前
uni-app小程序前端开发笔记(更新中)
前端·笔记·小程序·uni-app
喵喵虫2 天前
uniapp修改封装组件失败 styleIsolation
uni-app
游戏开发爱好者82 天前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
宠友信息2 天前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
“负拾捌”2 天前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别