vue監(jiān)聽(tīng)瀏覽器返回

需求

我在某個(gè)頁(yè)面用了緩存,假如點(diǎn)擊了瀏覽器返回按鈕,需要清除緩存信息

代碼

監(jiān)聽(tīng)返回

mounted () {
    if (window.history && window.history.pushState) {
        // 向歷史記錄中插入了當(dāng)前頁(yè)
        history.pushState(null, null, document.URL);
        window.addEventListener('popstate', this.goBack, false);
    }
},
destroyed () {
    window.removeEventListener('popstate', this.goBack, false);
},
methods: {
    goBack () {
        // console.log("點(diǎn)擊了瀏覽器的返回按鈕");
        sessionStorage.clear();
        window.history.back();
    },
} 

因?yàn)檫@個(gè)頁(yè)面有跳轉(zhuǎn)其他頁(yè)面的路由,所以在組件的路由鉤子里也清了緩存

beforeRouteLeave (to, from , next) {
    sessionStorage.clear();
    next()
},

禁用返回

mounted () {
    if (window.history && window.history.pushState) {
        // 向歷史記錄中插入了當(dāng)前頁(yè)
        history.pushState(null, null, document.URL);
        window.addEventListener('popstate', this.goBack, false);
    }
},
destroyed () {
    window.removeEventListener('popstate', this.goBack, false);
},
methods: {
    goBack () {
        // console.log("點(diǎn)擊了瀏覽器的返回按鈕");
        history.pushState(null, null, document.URL);
    },
} 

history對(duì)象

window可以省略,直接使用history
1、window.history.back() : 后退
2、window.history.forward() : 前進(jìn)
3、window.history.go(num) : 前進(jìn)或后退指定數(shù)量歷史記錄

window.history.go(1)
前進(jìn)
window.history.go(-1)
后退
window.history.go(0)
刷新

4、window.history.pushState(state, title, url)
存儲(chǔ)當(dāng)前歷史記錄點(diǎn)

state:一個(gè)對(duì)象,可以添加相關(guān)信息
title:歷史記錄的標(biāo)題
url:創(chuàng)建的歷史記錄的鏈接

5、window.history.replaceState(state, title, url)
替換當(dāng)前歷史記錄點(diǎn)

6、popstate
history 實(shí)體改變時(shí)觸發(fā)的事件,監(jiān)聽(tīng)歷史記錄點(diǎn)

7、window.history.state
獲取 history 實(shí)體中的 state 對(duì)象

history.go(0) 和 location.reload() 的區(qū)別

一、location.reload()
默認(rèn)參數(shù)為false,即location.reload(false)

1、location.reload(false):
會(huì)用 HTTPIf-Modified-Since 來(lái)檢測(cè)服務(wù)器上的文檔是否已改變
如果文檔已改變,從服務(wù)端再次下載該文檔
如果文檔未改變,從緩存中裝載文檔
作用等同于點(diǎn)擊瀏覽器的刷新按鈕 (F5)

2、location.reload(true):
繞過(guò)緩存,從服務(wù)器上重新下載該文檔
作用等同于點(diǎn)擊瀏覽器的刷新按鈕,同時(shí)按住Shift (Shift+F5)

二、history.go(0)
直接讀取緩存數(shù)據(jù),不會(huì)從服務(wù)器端獲取數(shù)據(jù)

history.go(-1) 和 history.back() 的區(qū)別

一、history.go(-1)
后退并刷新,原頁(yè)面表單中的內(nèi)容會(huì)丟失
二、history.back()
后退,原頁(yè)面表單中的內(nèi)容會(huì)保留

網(wǎng)站導(dǎo)航

網(wǎng)站導(dǎo)航

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容