vue監(jiān)聽瀏覽器原生返回按鈕,進(jìn)行路由轉(zhuǎn)跳操作
今天測試給我報(bào)了個bug說點(diǎn)擊瀏覽器返回頁數(shù)據(jù)顯示的不對,我查了半天原因:需要監(jiān)聽瀏覽器的回退按鈕,并阻止其默認(rèn)事件。
具體操作方法如下:
1、掛載完成后,判斷瀏覽器是否支持popstate
mounted(){ if (window.history && window.history.pushState) { history.pushState(null, null, document.URL); window.addEventListener(’popstate’, this.cancel, false); } },
2、頁面銷毀時,取消監(jiān)聽。否則其他vue路由頁面也會被監(jiān)聽
destroyed(){ window.removeEventListener(’popstate’, this.cancel, false); }
3、將監(jiān)聽操作寫在methods里面,removeEventListener取消監(jiān)聽內(nèi)容必須跟開啟監(jiān)聽保持一致,所以函數(shù)拿到methods里面寫
cancel: function() { if(this.orderId){ this.$router.push({ name:'orderList', params: {id:this.orderId},}); }else{ this.$router.go(-1); } },
補(bǔ)充知識:vue-router組件內(nèi)導(dǎo)航守衛(wèi)判斷返回按鈕
組件內(nèi)導(dǎo)航守衛(wèi)會出現(xiàn)無法攔截$router.go(-1)或者物理返回按鈕,在攔截函數(shù)外包裹setTimeout即可。具體原因還未發(fā)現(xiàn)。
setTimeout(() => { this.$confirm(’編輯的頁面布局尚未保存,確定離開?’, ’提示’, { confirmButtonText: ’確定’, cancelButtonText: ’取消’, type: ’warning’ }).then(() => { next() return }).catch(() => { this.$message({ type: ’info’, message: ’已取消’ }) next(false) return }) }, 500)
以上這篇vue監(jiān)聽瀏覽器原生返回按鈕,進(jìn)行路由轉(zhuǎn)跳操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
