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

个人需求阐述:

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

页面A的核心代码如下:

<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. uni-app页面进行拦截处理方法

    2024-04-12 10:54:04       45 阅读
  2. uni-app 路由方式

    2024-04-12 10:54:04       35 阅读
  3. uniapp怎么进行页面

    2024-04-12 10:54:04       26 阅读
  4. React页面方式详解

    2024-04-12 10:54:04       51 阅读
  5. 页面几种方式

    2024-04-12 10:54:04       41 阅读
  6. springboot使用aop实现方法拦截处理

    2024-04-12 10:54:04       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-12 10:54:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-12 10:54:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-12 10:54:04       82 阅读
  4. Python语言-面向对象

    2024-04-12 10:54:04       91 阅读

热门阅读

  1. 容器化部署--知识点标记

    2024-04-12 10:54:04       52 阅读
  2. 每天学习一个Linux命令之pwd

    2024-04-12 10:54:04       39 阅读
  3. 基于springboot的大学城水电管理系统源码数据库

    2024-04-12 10:54:04       34 阅读
  4. 查看Tomcat和JDK版本信息(32位还是64位)

    2024-04-12 10:54:04       39 阅读
  5. L2-047 锦标赛

    2024-04-12 10:54:04       41 阅读
  6. node与npm常用命令

    2024-04-12 10:54:04       195 阅读
  7. 速盾:为什么会出现高防cdn?它适合哪些行业?

    2024-04-12 10:54:04       94 阅读