Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace one parameter in Vuejs router

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...

like image 601
David Heremans Avatar asked May 30 '19 18:05

David Heremans


1 Answers

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.

like image 184
Harshal Patil Avatar answered Oct 20 '22 23:10

Harshal Patil