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>
相关推荐
酷酷的鱼14 分钟前
2026 跨平台开发终极选型:Flutter, React Native 与 uni-app x 深度博标与规划指南
flutter·react native·uni-app
biyezuopinvip14 分钟前
基于uni-app和Express的问答对战小程序的设计与实现(论文)
小程序·uni-app·毕业设计·论文·express·毕业论文·问答对战小程序的设计与实现
2501_9159090618 小时前
Charles 抓不到包怎么办?iOS 调试过程中如何判断请求路径
android·ios·小程序·https·uni-app·iphone·webview
2501_9160074718 小时前
iOS和iPadOS文件管理系统全面解析与使用指南
android·ios·小程序·https·uni-app·iphone·webview
卜锦元19 小时前
EchoChat搭建自己的音视频会议系统01-准备工作
c++·golang·uni-app·node.js·音视频
敲敲了个代码21 小时前
让 Vant 弹出层适配 Uniapp Webview 返回键
前端·javascript·vue.js·学习·面试·uni-app
2501_915921431 天前
iOS App 开发阶段性能优化,观察 CPU、内存和日志变化
android·ios·性能优化·小程序·uni-app·iphone·webview
木子啊1 天前
UNIAPP国内房贷计算器
uni-app·房贷·房贷计算器·房贷利率·公积金贷款·商业贷款
游戏开发爱好者81 天前
在 iOS 开发、测试与上架过程中 如何做证书管理
android·ios·小程序·https·uni-app·iphone·webview
码界奇点1 天前
基于Spring Boot 3与UniApp的跨平台新零售电商系统设计与实现
spring boot·uni-app·毕业设计·uniapp·零售·源代码管理