Guide to creating flexible routes with multiple changing parameters in Vue 3 using Vue Router

What is the best way to implement dynamic routes with multiple dynamic parameters in any order using Vue 3 and Vue Router?
These parameters should be able to be passed in any order.

In our web application, we have over 500 views which makes it impractical to set each one in the routes file. Therefore, we need to resolve the routes at runtime by loading the necessary component (.vue) when required.

Consider a view named "Products" where clients can use multiple filter options, passing them in the URL while filtering. The number of parameters they pass varies from 0 to more than 10 depending on their filtering requirements.

Users should be able to create URLs like the examples below:
www.webapp.com/products

www.webapp.com/products/color/red

www.webapp.com/products/brand/myBrand/color/green

www.webapp.com/products/size/36/brand/myBrand

and many other dynamic possibilities.

I attempted to add routes using wildcard *, but had no success.
Here are some examples of what I tried:
{path: '/products/:(.*)', ...}

{path: '/products/:params(.*)', ...}

{path: '/products/:(.*)*', ...}
{path: '/products/:params(.*)*', ...}

{path: '/products/*', ...}
{path: '/products-*', ...}

None of these attempts worked as expected. Some threw errors, while others removed parameters from the URL, leaving only /products. In all cases, this.$route.params remained empty.

How can I successfully create dynamic routes with multiple dynamic parameters in any order using Vue 3 and Vue Router?

Please note that for the sake of 'Friendly URL,' we cannot use queries because they are considered ugly
(e.g.,

products?color=red&size=10&brand=my%20brand
)

Answer №1

Your attempts may have been unsuccessful because of a mix-up in syntax between named parameters (indicated by a colon followed by the parameter name) and unnamed parameters (specified as `(.*)`).

To handle zero or more named parameters (such as `myParams`), you should follow this pattern:

:myParams*

I suggest using a props function to properly parse the route parameters and pass them to the component as props. This approach centralizes the parameter formatting and removes the need for the component to dissect the route:

const routes = [
  {
    path: '/products/:myParams*',
    component: () => import('@/components/Products.vue'),

    // converting key-value pairs into an object
    props: route => {
      const params = route.params.myParams;
      const props = {};
      for (let i = 0; i < params.length; i += 2) {
        const value = i + 1 < params.length ? params[i + 1] : null;
        props[params[i]] = value;
      }
      return props;
    }
  }
]

Check out this demonstration for further clarification: demo

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

Incorporate an additional javascript document into a VueJS component

What is the most efficient method to include Javascript files in Vue.js components? ...

Create a PDF document and provide a reply

Recently, I encountered an issue while trying to generate a PDF using KnpSnappyBundle on Symfony. Upon running a route through AJAX, the code executes without errors but fails to produce the PDF file. The objective is to create a PDF in a new tab or wind ...

Using jQuery to select the next table cell vertically

Is there a way to utilize jQuery to access the cell (td) directly below a given cell in a traditional grid-layout HTML table (where each cell spans only one row and column)? I understand that the code below will assign nextCell to the cell immediately to ...

Tips for organizing checkboxes in rows horizontally

My question is related to this issue I am trying to arrange my checkboxes in 4 columns horizontally <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> ...

Encountering an issue with Vuex action dispatch when using electron

I'm currently working on an Electron app with Vuex. The store is set up for the entire application using modules. One of my test modules is Browser.js: export default { namespaced: true, state: { currentPath: 'notSet' }, mutatio ...

Utilizing Firebase login to integrate with Facebook API

My current setup involves Facebook authentication tied to login, all managed through Firebase. However, I now face the need to make an API call to Facebook using 'me/friends/' endpoint without having to send another request since I am already log ...

Tips for setting up npm dependencies in a subfolder

Within the main directory, I have a package.json file that contains this command: "install": "cd packages/my-package && yarn". Every time I execute yarn run install, my intention is for it to enter into the specified package, set up the node modul ...

Challenges encountered when using node.js to write binary data

I've been attempting to write the binary body of a request to a file, but I'm encountering some issues. Although the file is successfully created on the server, I'm unable to open it and am receiving a 'Fatal error: Not a png' mess ...

Comparing obj.hasOwnProperty(key) with directly accessing obj[key]

Consider the scenario where I need to determine if a property exists within an Object. A comparison between two methods caught my attention: if(object.hasOwnProperty(key)) { /* perform this action */ } OR if(object[key]) { /* perform this action */ ...

The technique of using Javascript x to escape characters is

I've come across a handful of other software programs that feature a similar construct: let str = '\x32\x20\x60\x78\x6e\x7a\x9c\x89'; As I experimented with the sequence of numbers and letters within ...

Can you explain the process that takes place when require("http").Server() is called with an Express application passed in as a parameter?

As I was exploring the Socket.io Chat Demo found at this link: http://socket.io/get-started/chat/, I came across their require statements which left me feeling confused. var app = require('express')(); var http = require('http').Server ...

What is the proper way to implement JQuery within a constructor function contained in a JavaScript namespace?

Yesterday I ran into a problem when asking about using JQuery inside a JavaScript constructor function within a namespace. There was a bug in my code that caused me to get the answer to the wrong question. var NS=NS||{}; NS.constructor=function() { t ...

Deleting an element from a JavaScript array

I have a collection of javascript functions that manage intervals by setting and clearing them. The intervals are stored in an array called intervals[]. config: { settings: { timezone: 'Australia/Perth,', base_url: location.p ...

FusionCharts Gauges may share similar code, but each one produces a unique output

Currently, I am developing a project that involves creating a dashboard with 3 gauges. These gauges are enclosed in bootstrap cards with a column value set to 4. In the layout of the dashboard, these 3 cards are positioned next to each other. I have succe ...

Tips for modifying javascript code to have popups appear as bPopup instead of in a separate popup window

Is there a way to modify the following code so that popup windows open as dpopups instead of just in a new popup window ()? $(document).ready(function() { var table = $('#taulu').DataTable( { "ajax": "taulu.php", "columnDefs" ...

Automatic popup updates when submitting a form in a Chrome extension

Looking to develop a chrome extension popup window that, when clicked, will present a form for users to input their name and college. The goal is to save this data in chrome storage and then replace the popup with a new window displaying a greeting message ...

Discover the key to optimizing your JavaScript development workflow by automating project structures and eliminating the need to start from scratch

I was looking for a way to streamline the process of setting up project structures for my projects so that I could utilize ALE linting and fixing without any hassle. After trying out one method, I'm confident that there must be a more efficient soluti ...

What is the best way to incorporate jQuery and its plugins into a Vue component?

Is there a way to include jQuery plugins in a Vue application and use them inside the mounted hook? I know that jQuery can be imported via "import" inside a component (in the export default object) and is used in the life-cycle hook called "mounted." Howev ...

Converting JSON data into a JavaScript array and storing it in a variable

Currently, I am delving into the world of JavaScript and my instructor has assigned a task that involves utilizing information from a JSON file within our JavaScript code. The issue I'm facing is deciphering how to effectively convert the JSON data i ...

Gradually appear with jQuery while maintaining current position

Exploring Display Options In my current setup, I have text that initially has a display:none property, and jQuery is applied to fadeIn() the content. The challenge lies in the fact that since the text is centered, as each word appears, the positioning on ...