Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  27] [ 3]  / answers: 1 / hits: 16047  / 5 Years ago, thu, may 30, 2019, 12:00:00

We have a multi-level multi-tenant application, where the hostname identifies the 'supplier' account, but the customer account is actually part of the URL.



For instance, we have routes set up as follows:



/:locale/app/:customer_id/invoices


At the top of the page, we have a drop down with all customer ID's the user has access to. The idea basically is that when a user changes the customer, the route changes from /nl/app/4/invoices to /nl/app/5/invoicesfor instance. So basically what I want to do is tell VueJs router to take the current route, and just change one parameter value in that route.



As you can imagine: the same goes for the :locale parameter where we basically have a language switch on top.



I know you can use $router.push in combination with a named route, and pass the current params in, replacing the params I want to update, but that would mean I'd have to name every route, and I'd need to know what the routes name is when I do an update.



Isn't there a way to just ask VueJS Router to give me the current route, and update one parameter?



I've searched a lot on SO as well as through other resources, but so far did not get a good result...


More From » vue.js

 Answers
7

You do not really need named routes or manual path creation for this functionality. Router's push and replace methods support partial patches. You can build a simple reusable function to achieve this:


// This function expects router instance and params object to change
function updatePathParams($router, newParams) {

// Retrieve current params
const currentParams = $router.currentRoute.params;

// Create new params object
const mergedParams = { ...currentParams, newParams };

// When router is not supplied path or name,
// it simply tries to update current route with new params or query
// Almost everything is optional.
$router.push({ params: mergedParams });
}

In your component, you can use it like:


onClickHandler() {
updatePathParams(this.$router, { locale: 'en-us' });

// Sometime later
updatePathParams(this.$router, { customer_id: 123 });
}


Also, here I merged the params object with existing values to illustrate the idea. In reality, you don't need to pass all the params. If you wish to change just one param say, customer_id, then simply do: $router.push({ params: { customer_id: 1234 } }). Vue-Router is smart enough to retain the same route and keep other params (locale here) unchanged.



[#52059] Wednesday, May 22, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cameron

Total Points: 591
Total Questions: 112
Total Answers: 88

Location: Botswana
Member since Sat, Jan 7, 2023
1 Year ago
;