前言
分享頁(yè)面時(shí),希望點(diǎn)擊瀏覽器回退按鈕,回到項(xiàng)目首頁(yè),增加訪問(wèn)量。
需要監(jiān)聽(tīng)瀏覽器的回退按鈕,并阻止其默認(rèn)事件。
具體步驟如下:
1、掛載完成后,判斷瀏覽器是否支持popstate
1
2
3
4
5
6
|
mounted(){ if (window.history && window.history.pushState) { history.pushState( null , null , document.URL); window.addEventListener( 'popstate' , this .goBack, false ); } }, |
2、頁(yè)面銷毀時(shí),取消監(jiān)聽(tīng)。否則其他vue路由頁(yè)面也會(huì)被監(jiān)聽(tīng)
1
2
3
|
destroyed(){ window.removeEventListener( 'popstate' , this .goBack, false ); }, |
3、將監(jiān)聽(tīng)操作寫在methods里面,removeEventListener取消監(jiān)聽(tīng)內(nèi)容必須跟開(kāi)啟監(jiān)聽(tīng)保持一致,所以函數(shù)拿到methods里面寫
1
2
3
4
5
6
|
methods:{ goBack(){ this .$router.replace({path: '/' }); //replace替換原路由,作用是避免回退死循環(huán) } } |
附:popstate用來(lái)做什么的?
popstate的怎么用?
HTML5的新API擴(kuò)展了window.history,使歷史記錄點(diǎn)更加開(kāi)放了。可以存儲(chǔ)當(dāng)前歷史記錄點(diǎn)pushState、替換當(dāng)前歷史記錄點(diǎn)replaceState、監(jiān)聽(tīng)歷史記錄點(diǎn)popstate。
pushState、replaceState兩者用法差不多。
使用方法:
1
2
|
history.pushState(data,title,url); //其中第一個(gè)參數(shù)data是給state的值;第二個(gè)參數(shù)title為頁(yè)面的標(biāo)題,但當(dāng)前所有瀏覽器都忽略這個(gè)參數(shù),傳個(gè)空字符串就好;第三個(gè)參數(shù)url是你想要去的鏈接; |
replaceState用法類似,例如:history.replaceState("首頁(yè)","",location.href+ "#news");
總結(jié)
到此這篇關(guān)于vue瀏覽器返回監(jiān)聽(tīng)的文章就介紹到這了,更多相關(guān)vue瀏覽器返回監(jiān)聽(tīng)內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/bocongbo/article/details/81667054