赞
踩
个人需求阐述:
当用户在页面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中处理。
本文是作者原创,大家在使用中有问题,欢迎留言评论!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。