当前位置:   article > 正文

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

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

个人需求阐述:

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

页面A的核心代码如下:

  1. <button @click="goPage">离开此页面,前往B页面</button>
  2. import { onLoad, onUnload } from '@dcloudio/uni-app'
  3. onLoad(() => {
  4. console.log('页面加载了')
  5. uni.addInterceptor('navigateTo', interceptor)
  6. })
  7. onUnload(() => {
  8. console.log('页面被卸载了')
  9. uni.removeInterceptor('navigateTo')
  10. })
  11. // 拦截器
  12. const interceptor:UniApp.InterceptorOptions= {
  13. async invoke(options: UniApp.NavigateToOptions) {
  14. const flag = await leaveBeforePage()
  15. if (flag) {
  16. return options
  17. } else {
  18. return false
  19. }
  20. }
  21. }
  22. // 离开页面前的判断
  23. const leaveBeforePage = (): Promise<boolean> => {
  24. return new Promise((resolve) => {
  25. uni.showModal({
  26. content: '有信息未被保存,确认离开当前页面?',
  27. showCancel: true,
  28. success: ({ confirm }) => {
  29. if (confirm) {
  30. resolve(true)
  31. } else {
  32. resolve(false)
  33. }
  34. }
  35. })
  36. })
  37. }
  38. // 手动点击返回页面B
  39. const goPage = () => {
  40. uni.navigateTo({ url: '/pages/home/home' })
  41. }

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/429257
推荐阅读
相关标签
  

闽ICP备14008679号