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

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

相关推荐
云上凯歌5 小时前
01_AI工具平台项目概述.md
人工智能·python·uni-app
郑州光合科技余经理5 小时前
O2O上门预约小程序:全栈解决方案
java·大数据·开发语言·人工智能·小程序·uni-app·php
2501_916008896 小时前
在不越狱前提下导出 iOS 应用文件的过程,访问应用沙盒目录,获取真实数据
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_915106326 小时前
Android和IOS 移动应用App图标生成与使用 Assets.car生成
android·ios·小程序·https·uni-app·iphone·webview
木子啊6 小时前
UNIAPP移动端瀑布流列表,支持APP、微信小程序、H5
uni-app·瀑布流·两列排序
2501_915918416 小时前
Mac 抓包软件有哪些?Charles、mitmproxy、Wireshark和Sniffmaster哪个更合适
android·ios·小程序·https·uni-app·iphone·webview
2501_915106326 小时前
iOS 抓包绕过 SSL 证书认证, HTTPS 暴力抓包、数据流分析
android·ios·小程序·https·uni-app·iphone·ssl
WeiAreYoung6 小时前
uni-app xcode 制作iOS Notification Service Extension 远程推送图文原生插件
ios·uni-app·xcode
2501_9159214314 小时前
iOS App 电耗管理 通过系统电池记录、Xcode Instruments 与克魔(KeyMob)组合使用
android·ios·小程序·https·uni-app·iphone·webview
2501_915918411 天前
iOS App 测试方法,Xcode、TestFlight与克魔(KeyMob)等工具组合使用
android·macos·ios·小程序·uni-app·iphone·xcode