亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

解決vue中使用history.replaceState?更改url?vue?router?無法感知的問題

 更新時間:2022年09月19日 11:04:15   作者:Gleason.  
這篇文章主要介紹了vue中使用history.replaceState?更改url?vue?router?無法感知的問題,本文給大家分享修復這個問題的方法,需要的朋友可以參考下

vue中使用history.replaceState 更改url vue router 無法感知的問題

描述

最近做一個需求,URL更新不刷新頁面,在網上找了 好多文章都說 router.replace 更新URL不會刷新頁面(前提是路由為 history 模式),我也用了,一開始是沒問題的,可以實現需求,但是后來URL變得越來越復雜,會導致URL更新時,會觸發(fā)mounted執(zhí)行,這樣的話頁面就會刷新,后來更換了 history.replaceState API 更新URL,頁面確實不刷新了,但是也帶來了新的問題,就是 vue router 無法感知到URL的變化 ,舉個例子吧

假設

url:www.eg.com/index?a=1
使用router.replace 更新 url this.$router.replace('www.eg.com/index?a=2')
輸出 fullpath console.log(this.$route.fullPath) => www.eg.com/index?a=2
這個結果是對的;

如果使用 history.replaceState 更新url就會出現問題
使用 history.replaceState 更新 url history.replaceState(null,'','www.eg.com/index?a=2');url 確實是更新了,
輸出 fullpath console.log(this.$route.fullPath) => www.eg.com/index?a=1

結論: this.$route 就沒有被更新

如何修復這個問題

// 這個 stateObj 其實就是查詢參數的 key value 轉換成的對象
const stateObj = {
	a:2,
	b:3
}
history.replaceState(stateObj, 'title', 'www.eg.com/index?a=2&b=3')
// 將原來的 this.$route 克隆一份
const _route = Object.assign({},this.$route);
// 更新 fullPath 
_route.fullPath = 'www.eg.com/index?a=2&b=3'
// 更新 參數
_route.params = stateObj
// 調用 router.history 里的更新方法 cb 傳入最新的route就可以了
this.$router.history.cb(_route)
// 我們再次輸出 fullPath
console.log(this.$route.fullPath) => 'www.eg.com/index?a=2&b=3'

問題到這里就修復了

其實 使用 history api 更新 URL 這個功能 react router 早在 V3 版本就已經實現了,話說這已經是 5 ,6 年前的問題了, 也就是說 使用 history api 更新url react router 是可以感知到 URL 變化的并且會被記錄,但是vue沒有,還好有router.history.cb這個回掉,不然神仙都解決不了這個問題。。。。

到此這篇關于vue中使用history.replaceState 更改url vue router 無法感知的問題的文章就介紹到這了,更多相關vue url vue router內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論