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