添加一个参数
当前 URL:http://localhost/home?keyword=example

this.$router.replace({ query: { ...this.$route.query, code: '1' } })

最终 URL:http://localhost/home?keyword=example&code=1

删除一个参数
我所使用的 Vue Router 版本为 3.0.3,删除参数比较麻烦。

当前 URL:http://localhost/home?keyword=example&code=1
无效的方法

delete this.$route.query.code
this.$router.replace({ query: this.$route.query }) // 地址栏无反应

有效的方法

let newQuery = JSON.parse(JSON.stringify(this.$route.query)) // 深拷贝
delete newQuery.code
// 如果有引入 lodash, 可以写成: let newQuery = _.omit(this.$route.query, 'code')
this.$router.replace({ query: newQuery })

最终 URL:http://localhost/home?keyword=example

后记
使用 this.$router.replace() 以及 this.$router.push() 时,地址栏变化是有延后的,且这个延后无法通过 this.$nextTick() 预测。

以下场景:
微信 OAuth 回跳到我们的页面时,会在 URL 追加 code 参数用于认证,我们成功获得 code 后想要从地址栏去掉它,同时还要配置微信 JS SDK。
配置微信 JS SDK 需要当前页面地址(window.location.href.split('#')[0]),而我们去掉 code 会导致地址改变。
地址栏实际改变完成的时间是不可预测的,而配置微信 JS SDK 有成功回调,所以需要先配置微信 JS SDK,再处理地址栏。

参考资料:https://stackoverflow.com/questions/48700584/vuejs-how-to-remove-parameter-from-url