欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

描述

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

假設(shè)

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
這個(gè)結(jié)果是對(duì)的;

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

結(jié)論: this.$route 就沒有被更新

如何修復(fù)這個(gè)問題

// 這個(gè) stateObj 其實(shí)就是查詢參數(shù)的 key value 轉(zhuǎn)換成的對(duì)象
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'
// 更新 參數(shù)
_route.params = stateObj
// 調(diào)用 router.history 里的更新方法 cb 傳入最新的route就可以了
this.$router.history.cb(_route)
// 我們?cè)俅屋敵?fullPath
console.log(this.$route.fullPath) => 'www.eg.com/index?a=2&b=3'

問題到這里就修復(fù)了

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

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

相關(guān)文章

最新評(píng)論