uni-app中,页面跳转前,进行拦截处理的方法

个人需求阐述:

当用户在页面A中 ,填写了内容之后,没有点击"保存/确定" ,直接通过点击返回按钮或者手机的物理返回键直接返回时,需要给出一个二次确认的弹层,当用户点击确定离开之后,跳转到页面B,点击取消,页面不跳转

页面A的核心代码如下:

TypeScript 复制代码
<button @click="goPage">离开此页面,前往B页面</button>

import { onLoad, onUnload } from '@dcloudio/uni-app'

onLoad(() => {
  console.log('页面加载了')
  uni.addInterceptor('navigateTo', interceptor)
})

onUnload(() => {
  console.log('页面被卸载了')
  uni.removeInterceptor('navigateTo')
})

// 拦截器
const interceptor:UniApp.InterceptorOptions= {
    async invoke(options: UniApp.NavigateToOptions) {
      const flag = await leaveBeforePage()
      if (flag) {
        return options
      } else {
        return false
      }
    }
  }

// 离开页面前的判断
const leaveBeforePage = (): Promise<boolean> => {
  return new Promise((resolve) => {
    uni.showModal({
        content: '有信息未被保存,确认离开当前页面?',
        showCancel: true,
        success: ({ confirm }) => {
          if (confirm) {
            resolve(true)
          } else {
            resolve(false)
          }
        }
      })
  })
}

// 手动点击返回页面B
const goPage = () => {
  uni.navigateTo({ url: '/pages/home/home' })
}

注意:如果是点击tabBar的按钮进行切换时,页面离开时的拦截器会无效,tabBar页面的拦截需要在onShow中处理。

本文是作者原创,大家在使用中有问题,欢迎留言评论!

相关推荐
PedroQue9915 小时前
Vue Router 4.x风格导航守卫全面升级
前端·uni-app
Haibakeji18 小时前
APP小程序定制开发项目频繁延期?前期规避方法与落地避坑指南
小程序·uni-app·软件需求
anyup19 小时前
迁移uni-app x,我是如何让 AI 把我一步步搞崩溃的...
前端·uni-app·trae
2501_9160074720 小时前
申请 iOS 推送证书并配置 APNs 群发推送教程
android·ios·小程序·https·uni-app·iphone·webview
博客zhu虎康21 小时前
uni-app云打包显示编译成功,但是一直没有进入打包队列,后面也一直没反应
uni-app
JavaDog程序狗2 天前
【指南】uni-app微信小程序多环境CI-CD完全指南
ci/cd·uni-app·jenkins
PedroQue992 天前
uni-router v2.1.0 升级:导航守卫全面支持返回值模式
前端·uni-app
2501_915909063 天前
iOS test 测试怎么做?功能、性能、兼容、稳定与安全五类测试指南
android·ios·小程序·https·uni-app·iphone·webview
游戏开发爱好者84 天前
App Store 上传 IPA 自动化,.p8 密钥认证与 CI/CD 接入实战
android·运维·ci/cd·小程序·uni-app·自动化·iphone
游戏开发爱好者84 天前
iOS 推送怎么配置,APNs 推送证书、设备库与群发
android·ios·小程序·https·uni-app·iphone·webview