一起做網(wǎng)站鄭州電商網(wǎng)站入口
個(gè)人需求闡述:
? ? ? ? 當(dāng)用戶在頁面A中,填寫了內(nèi)容之后,沒有點(diǎn)擊“保存/確定”,直接通過點(diǎn)擊返回按鈕或者手機(jī)的物理返回鍵直接返回時(shí),需要給出一個(gè)二次確認(rèn)的彈層,當(dāng)用戶點(diǎn)擊確定離開之后,跳轉(zhuǎn)到頁面B,點(diǎn)擊取消,頁面不跳轉(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: '有信息未被保存,確認(rèn)離開當(dāng)前頁面?',showCancel: true,success: ({ confirm }) => {if (confirm) {resolve(true)} else {resolve(false)}}})})
}// 手動(dòng)點(diǎn)擊返回頁面B
const goPage = () => {uni.navigateTo({ url: '/pages/home/home' })
}
注意:如果是點(diǎn)擊tabBar的按鈕進(jìn)行切換時(shí),頁面離開時(shí)的攔截器會(huì)無效,tabBar頁面的攔截需要在onShow中處理。
本文是作者原創(chuàng),大家在使用中有問題,歡迎留言評(píng)論!