如何将 router.push 用于相同路径,Vue.js 中的不同查询参数
How to use router.push for same path, different query parameter in Vue.js
当前url是
/?type=1
我想在此页面上使用 router.push。
this.$router.push('/?type=2');
但这会导致 NavigationDuplicated 错误。
我不想使用像
这样的参数
/:type
请看这个GitHub issue。他们正在使用 this.$router.replace
,但我想它与您使用 this.$router.push
时的根本原因相同。建议的解决方案/解决方法是使用链接到 $router
调用的空 catch
,因此:
this.$router.push('/?type=2').catch(err => {})
编辑
您也可以将查询参数作为对象传递给 this.$router.push
的第二个参数:
this.$router.push({ query: { type: 2 } })
那是因为它与你现在的路径没有什么不同。
如果 type
的值不同,它不会给你 NavigationDuplicated
错误。
您也可以像下面这样分隔查询,以确保框架可以理解它:
this.$router.push({
path: '/',
query: { type: 2 },
});
Aliraza 已经回答了你的问题,但我分享这个答案是因为我看到你的评论询问,组件不重新渲染,对于重新渲染组件你需要像这样观察参数:
watch: {
'$route.params': 'functionToRunWhenParamsChange',
}
<router-view :key="$route.fullPath"
当前url是
/?type=1
我想在此页面上使用 router.push。
this.$router.push('/?type=2');
但这会导致 NavigationDuplicated 错误。
我不想使用像
这样的参数/:type
请看这个GitHub issue。他们正在使用 this.$router.replace
,但我想它与您使用 this.$router.push
时的根本原因相同。建议的解决方案/解决方法是使用链接到 $router
调用的空 catch
,因此:
this.$router.push('/?type=2').catch(err => {})
编辑
您也可以将查询参数作为对象传递给 this.$router.push
的第二个参数:
this.$router.push({ query: { type: 2 } })
那是因为它与你现在的路径没有什么不同。
如果 type
的值不同,它不会给你 NavigationDuplicated
错误。
您也可以像下面这样分隔查询,以确保框架可以理解它:
this.$router.push({
path: '/',
query: { type: 2 },
});
Aliraza 已经回答了你的问题,但我分享这个答案是因为我看到你的评论询问,组件不重新渲染,对于重新渲染组件你需要像这样观察参数:
watch: {
'$route.params': 'functionToRunWhenParamsChange',
}
<router-view :key="$route.fullPath"