代碼
監聽返回
mounted () { if (window.history && window.history.pushState) { // 向歷史記錄中插入了當前頁 history.pushState(null, null, document.URL); window.addEventListener('popstate', this.goBack, false); } }, destroyed () { window.removeEventListener('popstate', this.goBack, false); }, methods: { goBack () { // console.log("點擊了瀏覽器的返回按鈕"); sessionStorage.clear(); window.history.back();
history.pushState(null, null, document.URL);
},
}
因為這個頁面有跳轉其他頁面的路由,所以在組件的路由鈎子里也清了緩存
beforeRouteLeave (to, from , next) {
sessionStorage.clear();
next()
},
禁用返回
mounted () { if (window.history && window.history.pushState) { // 向歷史記錄中插入了當前頁 history.pushState(null, null, document.URL); window.addEventListener('popstate', this.goBack, false); } }, destroyed () { window.removeEventListener('popstate', this.goBack, false); }, methods: { goBack () { // console.log("點擊了瀏覽器的返回按鈕"); history.pushState(null, null, document.URL); }, }
history對象
window
可以省略,直接使用history
1、window.history.back() : 后退
2、window.history.forward() : 前進
3、window.history.go(num) : 前進或后退指定數量歷史記錄
window.history.go(1) 前進 window.history.go(-1) 后退 window.history.go(0) 刷新
4、window.history.pushState(state, title, url)
存儲當前歷史記錄點
state:一個對象,可以添加相關信息
title:歷史記錄的標題
url:創建的歷史記錄的鏈接
5、window.history.replaceState(state, title, url)
替換當前歷史記錄點
6、popstate
history 實體改變時觸發的事件,監聽歷史記錄點
7、window.history.state
獲取 history 實體中的 state 對象
history.go(0) 和 location.reload() 的區別
一、location.reload()
默認參數為false,即location.reload(false)
1、location.reload(false):
會用 HTTP 頭 If-Modified-Since 來檢測服務器上的文檔是否已改變
如果文檔已改變,從服務端再次下載該文檔
如果文檔未改變,從緩存中裝載文檔
作用等同於點擊瀏覽器的刷新按鈕 (F5)
2、location.reload(true):
繞過緩存,從服務器上重新下載該文檔
作用等同於點擊瀏覽器的刷新按鈕,同時按住Shift (Shift+F5)
二、history.go(0)
直接讀取緩存數據,不會從服務器端獲取數據
history.go(-1) 和 history.back() 的區別
一、history.go(-1)
后退並刷新,原頁面表單中的內容會丟失
二、history.back()
后退,原頁面表單中的內容會保留
原文:https://blog.csdn.net/weixin_33953384/article/details/87518720