Donnie
Donnie

Reputation: 6351

Vue-Router: Globally Add Query Value to Routes

🏁 Goal

I'd like to add ?instance=123 to every route that is generated.

👾 Problem

I've added a guard to append the value before navigating to each route, but this approach does not work as expected.

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

How is this accomplished?

🕵️‍♂️ Context

Upvotes: 2

Views: 1104

Answers (2)

George
George

Reputation: 6739

Using the code from github posted by codeofsumit seems to achieve what you want:

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

What this does is adds the instance property to the query object, which is what you were doing in your attempt, but you were missing out the part where it has to call next with the modified object, otherwise it will just continue to the original route.

Upvotes: 4

bcjohn
bcjohn

Reputation: 2523

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

Upvotes: 0

Related Questions