例如提交訂單成功跳到了訂單詳情頁面,再返回就又到了提交訂單支付頁面
我們需要返回到其他頁面
1、掛載完成后,判斷瀏覽器是否支持popstate
mounted(){ if (window.history && window.history.pushState) { history.pushState(null, null, document.URL); window.addEventListener('popstate', this.goBack, false); } },
2、頁面銷毀時,取消監聽。否則其他vue路由頁面也會被監聽
destroyed(){ window.removeEventListener('popstate', this.goBack, false); },
3、將監聽操作寫在methods里面,removeEventListener取消監聽內容必須跟開啟監聽保持一致,所以函數拿到methods里面寫
methods:{ goBack(){ this.$router.replace({path: '/'}); //replace替換原路由,作用是避免回退死循環 } }