如何更改当前页面url
需求
跳转到当前页面后,在用户无操作无察觉情况下,更改浏览器地址栏中的URL(主要是要拼接上一些参数),用来当用户分析链接时,分享出去的链接可以是更准确的。
一般用于跳转至本页面时,一些参数尚不确定,需要JS脚本判断或者接口判断。
实现
使用window.history 来实现该需求:
- 判断当前环境是否支持history.replaceState
- 替换当前URL
// 设置当前url
setCurrentUrl () {
if (!!(window.history && history.pushState)) {
// 支持History API
if (!(this.$route.query.shopId || getHashUrlQuery('shopId'))) {
history.replaceState(null, null, window.location.href.split('#')[0] + '#/homePage?shopId=' + this.filter.ShopID + '&cityId=' + this.filter.CityID)
}
}
}
createtime:2018-11-16