代码之家  ›  专栏  ›  技术社区  ›  Donnie

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

  •  0
  • Donnie  · 技术社区  · 7 年前

    目标

    我想补充 ?instance=123 到生成的每个路由。

    问题

    在导航到每个路线之前,我添加了一个附加值的保护, but this approach 不能按预期工作。

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

    这是如何完成的?

    语境

    • “Vue路由器”:“^2.5.3”
    • “VUE”:“2.3.2”,
    2 回复  |  直到 7 年前
        1
  •  1
  •   George    7 年前

    使用来自的代码 github 张贴 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 对于修改后的对象,否则它将继续执行原始路由。

        2
  •  0
  •   bcjohn    7 年前
    router.beforeEach((to, from, next) => {
      to.query.instance = '123';
      next();
    });