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

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

相关推荐
脾气有点小暴15 小时前
scroll-view分页加载
前端·javascript·uni-app
脾气有点小暴18 小时前
uniapp自定义头部导航
前端·uni-app
前端 贾公子1 天前
[uniapp][swtich开关]阻止切换状态(类似阻止事件冒泡)
uni-app
雪芽蓝域zzs1 天前
uniapp基于picker选择器实现年月日时分秒
uni-app
niucloud-admin1 天前
本地开发部署——uniapp端站点部署
uni-app
毕设源码-郭学长2 天前
【开题答辩全过程】以 基于uni-app的维修上门服务小程序设计与实现为例,包含答辩的问题和答案
uni-app
xiaohe06012 天前
📦 Uni ECharts 是如何使用定制 echarts 的?一篇文章轻松掌握!
vue.js·uni-app·echarts
Front思2 天前
uniapp实现物流节点
uni-app
赵庆明老师2 天前
uniapp 微信小程序页面JS模板
javascript·微信小程序·uni-app
熬耶2 天前
uniapp 简单实现列表左滑操作
uni-app