How to replace one parameter in Vuejs router How to replace one parameter in Vuejs router vue.js vue.js

How to replace one parameter in Vuejs router


You do not really need named routes or manual path creation for this function. 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 changefunction 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(ths.$router, { locale: 'en-us' });  // Sometime later  updatePathParams(ths.$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.