In my application a user can have multiple characters (which he can use simultaneously on multiple tabs). A character is identified by a query parameter. Since there is only a single "logon" where the character id is set, I wanted to assign the character id globally to all routes and API urls.
With vue-resource I can intercept the request with something like this:
Vue.http.interceptors.push((request, next) => {
request.params['character'] = characterId
next()
})
I tried to do basically the same thing with vue-router, but doing so didn't change the URL of the next route. The parameter is present in the new route's route object, but the query param isn't appended to the URL (thus breaking F5/Refresh etc.)
this.$router.beforeEach((to, from, next) => {
to.query.character = characterId
next()
})
What I want to accomplish:
I want to add the character's id as a query parameter to all push calls on the router, so instead of:
this.$router.push({ name: 'location.index', query: { character: characterId }})
I can type:
this.$router.push({ name: 'location.index' }) // query parameter is added automatically here
You should pass the url path to the next function https://router.vuejs.org/en/advanced/navigation-guards.html
I want to do the same but haven't figured it out yet.
If I just pass the url to the next functions the query is missing which will result in a Maximum Call Stack size exceeded error (infinite loop).
ok this worked:
router.beforeEach((to, from, next) => {
if (!to.query.lang) {
to.query.lang = 'myValue';
next({ path: to.path, query: to.query });
} else {
next();
}
});
What's the reason why next() only accepts a query object and not also a params object?
I would like to be able to for example set a { redirect: to.fullPath } as params object so it would not be visible in the browser url.
@codeofsumit this did work but not solving your real problem
Most helpful comment
What's the reason why next() only accepts a query object and not also a params object?
I would like to be able to for example set a { redirect: to.fullPath } as params object so it would not be visible in the browser url.