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中处理。

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

相关推荐
中国胖子风清扬1 天前
GPUI 在 macOS 上编译问题排查指南
spring boot·后端·macos·小程序·rust·uni-app·web app
码云数智-园园2 天前
uni-app 实现物流进度跟踪功能:从 UI 到数据驱动的完整方案
ui·uni-app
予你@。4 天前
UniApp + Vue3 实现 Tab 点击滚动定位(微信小程序)
微信小程序·小程序·uni-app
游戏开发爱好者84 天前
完整教程:App上架苹果App Store全流程指南
android·ios·小程序·https·uni-app·iphone·webview
予你@。4 天前
uni-app progress 组件使用详解
uni-app
iOS阿玮4 天前
春节提审高峰来袭!App Store 审核时长显著延长。
uni-app·app·apple
2501_916007474 天前
ios上架 App 流程,证书生成、从描述文件创建、打包、安装验证到上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106325 天前
iPhone 文件管理,如何进行应用沙盒文件查看
android·ios·小程序·https·uni-app·iphone·webview
2501_915921435 天前
Fastlane 结合 AppUploader 来实现 CI 集成自动化上架
android·运维·ci/cd·小程序·uni-app·自动化·iphone
云游云记5 天前
vue2 vue3 uniapp (微信小程序) v-model双向绑定
微信小程序·uni-app·vue