一起做網(wǎng)站鄭州電商網(wǎng)站入口
個人需求闡述:
? ? ? ? 當用戶在頁面A中,填寫了內(nèi)容之后,沒有點擊“保存/確定”,直接通過點擊返回按鈕或者手機的物理返回鍵直接返回時,需要給出一個二次確認的彈層,當用戶點擊確定離開之后,跳轉(zhuǎn)到頁面B,點擊取消,頁面不跳轉(zhuǎn)
頁面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中處理。
本文是作者原創(chuàng),大家在使用中有問題,歡迎留言評論!