Vue-Router:全局向路由添加查询值

Vue-Router: Globally Add Query Value to Routes

目标

我想将 ?instance=123 添加到生成的每条路线中。

问题

我添加了一个守卫来在导航到每条路线之前附加值,but this approach 没有按预期工作。

router.beforeEach((to, from, next) => {
  next({ query: { instance: '123' } });
});

这是如何实现的?

️‍♂️背景

router.beforeEach((to, from, next) => {
  to.query.instance = '123';
  next();
});

使用 github posted by codeofsumit 中的代码似乎可以实现您想要的:

router.beforeEach((to, from, next) => {  
  if (!to.query.instance) {
    to.query.instance= '123';
    next({ path: to.path, query: to.query });
  } else {
    next();
  }
});

这样做是将 instance 属性 添加到查询对象中,这就是您尝试做的事情,但是您错过了它必须调用 next修改后的对象,否则就继续原路走。