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>
相关推荐
橘子编程19 小时前
UniApp跨端开发终极指南
开发语言·vue.js·uni-app
叱咤少帅(少帅)3 天前
Uniapp开发pc端,小程序和APK
小程序·uni-app
2501_915918413 天前
iOS性能测试工具 Instruments、Keymob的使用方法 不局限 FPS
android·ios·小程序·https·uni-app·iphone·webview
2501_915918414 天前
iOS 混淆流程 提升 IPA 分析难度 实现 IPA 深度加固
android·ios·小程序·https·uni-app·iphone·webview
前端 贾公子4 天前
解决uni-app 输入框,键盘弹起时页面整体上移问题
前端·vue.js·uni-app
Muchen灬4 天前
【uniapp】(5) 创建gitee仓库并推送源码
gitee·uni-app
Muchen灬4 天前
【uniapp】(6) uniapp中使用vuex
uni-app
2501_915909064 天前
React Native 上架 App Store:项目运行与审核构建的流程
android·ios·小程序·https·uni-app·iphone·webview
李庆政3704 天前
uniapp+unicloud打包部署微信小程序
微信小程序·小程序·uni-app