vue中使用history.replaceState 更改url vue router 无法感知的问题

vue中使用history.replaceState 更改url vue router 无法感知的问题

描述

最近做一个需求,URL更新不刷新页面,在网上找了 好多文章都说 router.replace 更新URL不会刷新页面(前提是路由为 history 模式),我也用了,一开始是没问题的,可以实现需求,但是后来URL变得越来越复杂,会导致URL更新时,会触发mounted执行,这样的话页面就会刷新,后来更换了 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这个回掉,不然神仙都解决不了这个问题。。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gleason.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值