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>
相关推荐
spmcor2 小时前
身份证读卡“无感登录”方案实践:从手动点击到自动检测
uni-app
PedroQue997 小时前
uni-router v1.8.0新增冷启动守卫补执行
前端·uni-app
PedroQue991 天前
uni-router v1.7.0重磅更新:守卫重定向自由掌控
前端·uni-app
一份执念3 天前
uni-app项目 (vue+vite + uni-UI)中引入umd格式JS文件,微信小程序中导入报错处理方案
前端·uni-app·echarts
PedroQue993 天前
V1.6.1性能优化:高频路径提速与代码精简
前端·uni-app
夏碧笔5 天前
uni-app跨端地图实战:用第三方LBS替代微信平台收费服务
uni-app
用户69903048487510 天前
try catch使用场景 处理同步代码错误兼容用的
javascript·uni-app
ITKEY_10 天前
uniapp微信开发者工具 更改AppID失败 touristappid
uni-app
Geek_Vison10 天前
APP瘦身实战:从80MB+砍到15MB——基于小程序容器技术剥离APP非核心业务的实践分享
小程序·uni-app·mpaas
CHB11 天前
HDC2026 演讲实录|AI 驱动的跨端进化:利用 uni-agent 快速构建高性能鸿蒙应用
uni-app·harmonyos