我在Vue Router遇到了一些奇怪的行为,路由器的行为根据输入对象的组装方式而有所不同。下面的代码示例是除组件的'methods'属性之外的代码示例。有关详细信息,请参阅我的代码示例中的注释。
switchLocale(newLocale) {
// this solution works
const route = {
name: this.$route.name,
query: {locale: newLocale},
params: this.$route.params,
};
console.log(JSON.stringify(route));
// {"name":"v.support.help","query":{"locale":"en"},"params":{}}
this.$router.replace(route);
// this solution does not change the route. I would expect it to work exactly like the solution above
/*
const {name, query, params} = this.$route;
let route = {name, query, params};
route.query.locale = newLocale;
console.log(JSON.stringify(route));
// {"name":"v.support.help","query":{"locale":"en"},"params":{}}
this.$router.replace(route);
*/
}
可能导致这种情况发生的原因是什么?
答案 0 :(得分:0)
在第二个代码中,您直接改变this.$route.query
对象并将其传递给this.$router.replace
。我猜vue-router将无法检测查询是否已更改,因为您改变了vue-router的内部状态。
不要改变this.$route
对象(或任何Vue的内部状态),否则事情可能无法正常工作。
如果要在引入或更改另一个查询参数时保留现有查询参数,则可以执行以下操作:
this.$router.replace({
query: Object.assign({}, this.$route.query, { locale: newLocale }),
// No need to specify route name and params, they will be preserved
});