Ways to substitute a single parameter within Vue.js router

We are working on a complex multi-level multi-tenant application, where the hostname is used to identify the 'supplier' account and the customer account is included in the URL structure.

For example, our routes are structured like this:

/:locale/app/:customer_id/invoices

On the webpage, there is a dropdown menu that displays all the customer IDs accessible to the user. The goal is for the user to be able to switch between customers, changing the route from /nl/app/4/invoices to /nl/app/5/invoices, for instance. So essentially, I am looking for a way to instruct the VueJs router to update only one parameter value within the current route.

This functionality also applies to the :locale parameter, where we have a language selector at the top of the page.

I am aware that you can use $router.push with a named route and pass in the current parameters, replacing the ones that need updating. However, this requires naming every single route and knowing the route's name when making an update.

Is there a simpler method to request VueJS Router to "provide me with the current route" and allow me to update a specific parameter?

I have conducted extensive research on Stack Overflow and other platforms but haven't found a satisfactory solution yet...

Answer №1

For achieving this functionality, there is no real need for named routes or manual path creation. The Router's push and replace methods actually support partial patches. You can create a simple reusable function to make it work:

// A function that requires router instance and new params object
function updatePathParams($router, newParams) {

  // Get the current params
  const currentParams = $router.currentRoute.params;

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

  // When no path or name is provided to the router,
  // it will simply try to update the current route with new params or query
  // Everything here is optional.
  $router.push({ params: mergedParams });
}

In your component, you can utilize it like this:

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

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

I have merged the params object with existing values to demonstrate the concept. In reality, not all the params need to be passed. If you only want to change one param such as customer_id, then just do:

$router.push({ params: { customer_id: 1234 } })
. Vue-Router automatically retains the same route while keeping other params (like locale in this case) unchanged.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with undefined object in ExpressJS PUT method

Attempting to utilize the PUT method for updating a record in my database, I encountered an issue with the object not being defined. ReferenceError: blogpost is not defined Following this tutorial for routing steps, I noticed that while the variable is d ...

"Create a React button component that, when clicked, navig

I'm currently developing a web application using React and bootstrap. I'm facing difficulties in redirecting the page to another one when applying onClick to buttons. After adding a href, I'm unable to navigate to another page. Do you think ...

Solution for Vue index.html Favicon problem

Having some trouble with my favicon.ico/png file in Vue 2.0 and Vue CLI 3.0. No matter what I try, it just won't work properly. I've located the problem to this specific issue. After running yarn build, the index.html file changes this line of ...

What is preventing the visibility of my invoice items when I try to make edits to my invoice?

Currently, I am utilizing Laravel 5.7 and VueJs 2.5.* in my project. The issue I am facing is related to a Bootstrap Model that I use for creating and editing TicketInvoice and its associated TicketInvocieItems. When I try to edit, the Bootstrap Model open ...

Hiding content and troubleshooting video playback problems in FancyBox

I'm facing an interesting issue. I've implemented FancyBox lightbox to showcase a "video" tag when users click on the image thumbnail, and it functions well with all varieties of HTML5 video. The challenge arises when testing in browsers older th ...

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

Adjust the appearance of elements depending on whether the user has activated dark mode or

What is the most efficient way to implement both dark and light themes in my Vue app? One option is to create a 'dark.scss' file and use the '!important' property to override styles defined in components. Another option is to utilize pr ...

Tips for monitoring changes in an array in Vue.js with a dynamic index value?

Currently, I am in the process of developing an application using Node.js and Vue. The data structure for my component is as follows: data() { return { campaign: { buses: [], weeks: [ { oneWayBuses: ...

Stripping out only the position attribute using jQuery

I have implemented a code with the following characteristics: The navigation items' texts are hidden behind certain Divs, which I refer to as Navigation Divs. When the mouse hovers over these pixels (navigation Divs), the text that is behind the ...

How come changes to the DOM are not recognized by subsequent DOM readings?

As I work on my Vue application, I have encountered a scenario involving an element with a data-range attribute defined as follows: :data-range="form.appearence.height_min + '/7'" The value of form.appearance.height_min is dependent on ...

Scraping the web with cheerio: Should we delete or disregard a child element?

There's a specific website I'm looking to scrape, and its structure is as follows: <p><strong>a certain heading:</strong> some information etc. blabla </p> <p><strong>another heading:</strong> more deta ...

MongoDB does not recognize Db.Collection as a valid function

A lot of people have been inquiring about this specific error, but after thorough investigation, I couldn't pinpoint a similar issue. So I'm reaching out in the hopes that someone might be able to identify and help rectify it. Let me provide som ...

Can a JavaScript class have a property that returns an array?

To those more experienced in node red development, this may be obvious, but I'll ask anyway. Within my node red flow, I have a function node containing a javascript class that only exposes static members. Here's an example: class MeasurementsLis ...

Avoid adding any empty entries to the list using jQuery

I have implemented a code to prevent any blank entries from being added to my list, and it seems to be working fine. However, I can't shake the feeling that there might be a better way to achieve this. Even though it functions correctly, it doesn&apos ...

Working with Ruby on Rails by editing a section of embedded Ruby code in a .js.erb file

Currently, I am in the process of developing a single-page website and have successfully implemented ajax loading of templates to insert into the main content section. However, I am encountering difficulties when trying to do this with multiple templates u ...

Manipulating a textarea in jQuery by inserting a string and selecting a specific portion of it

Just as seen on SO with the B button: **bold text** Including that bold text is automatically highlighted and the cursor is placed right before the b ...

Incorporate JSON data to display SVG images

As a beginner in web development, I have been honing my skills with the AngularJS framework due to its user-friendly nature. Currently, I'm working on pulling JSON data from an API using $http.get method. One of the fields contains an image source i ...

A perfectly organized and justified menu with evenly spaced horizontal list items

I couldn't find a solution to evenly spacing out a series of list items for a menu styled list. After realizing CSS alone wasn't enough, I decided to incorporate some javascript (jQuery). My goal was to have equal padding between each LI without ...

Highlighting menu elements when landing on a page and making another menu element bold upon clicking in WordPress

I've been searching extensively for a solution to this issue. I'm trying to make the menu item DE appear bold when entering the site, and if I click on EN, I want DE to return to normal (thin) font while EN becomes bold. You can find the site he ...

Employing a function to concatenate promises

In my coding process, I have come across a situation where I need to fetch content and then save it using two separate functions. Each function performs a different task based on the type of content provided. These functions act as helper functions in my o ...