Utilizing multiple optional key values in Vue Router

When working with vue-router, I am faced with the challenge of creating a route that can handle multiple optional parameters. For example, the route needs to be able to handle scenarios like:

/something/a/1/b/2/c/3
/something/a/1/b/2
/something/a/1/c/3
/something/b/2/c/3
/something/a/1
/something/b/2
/something/c/3
/something/

In these examples, letters represent keys and digits represent values.

This is how I approached the problem in my code:

const router = new VueRouter({
    mode: 'history',
    base: __dirname,
    routes: [
        { path: '/something/a/:a/b/:b/c/:c', component: MyComponent },
        { path: '/something/a/:a/b/:b', component: MyComponent },
        { path: '/something/a/:a/c/:c', component: MyComponent },
        { path: '/something/b/:b/c/:c', component: MyComponent },
        { path: '/something/a/:a', component: MyComponent },
        { path: '/something/b/:b', component: MyComponent },
        { path: '/something/c/:c', component: MyComponent },
        { path: '/something/', component: MyComponent },
    ]
})

I wonder if there is a way to achieve this using regex. Perhaps I could just use '/something/*' and then extract the parameters later? Also, all values are integers in this case.

Answer №1

After studying this particular example, I made a fascinating discovery that by utilizing parentheses and the symbol ?, I could create an optional path structure like this

/path/(foo/)?bar

Additionally, when enclosing the parentheses with parameter as well /path/(foo/:foo)?, the parameter's name will be directly interpreted as part of the URI (in this case, as :foo), resulting in only routes such as /path/ and /path/foo/:foo (where :foo is treated literally within the URI) being functional.

Realizing this limitation, I decided to leverage regex instead of a straightforward /something/*. I implemented the following regex

/something/(a/\\d+)?/(b/\\d+)?/(c/\\d+)?
(\\d+ representing digits but customizable for various purposes).

const router = new VueRouter({
    mode: 'history',
    base: __dirname,
    routes: [
        { path: '/something/(a/\\d+)?/(b/\\d+)?/(c/\\d+)?', component: MyComponent },
    ]
})

As a result, the values extracted within this.$route.params from a URI like /something/a/5/b/6/c/7 would be

{ 1: "b/6", 2: "c/7", pathMatch: "a/5" }

If any value remains unset, it defaults to undefined.

// /something/a/5/c/7
{ 1: undefined, 2: "c/7", pathMatch: "a/5" }

Subsequently, within my MyComponent, I enhanced the presentation of this.$route.params for better readability

export default {
    mounted() {
        console.log(this.$route.params);
        if (this.$route.params.pathMatch) {
            let res = this.$route.params.pathMatch.split("/");
            this.$route.params[res[0]] = res[1];
        }
        delete this.$route.params.pathMatch;
        if (this.$route.params[1]) {
            let res = this.$route.params[1].split("/");
            this.$route.params[res[0]] = res[1];
        }
        delete this.$route.params[1];
        if (this.$route.params[2]) {
            let res = this.$route.params[2].split("/");
            this.$route.params[res[0]] = res[1];
        }
        delete this.$route.params[2];
        console.log(this.$route.params);
    }
}

Potentially, there might be further refinements to this section (for instance, providing the anticipated key rather than using res[0] or streamlining the process iteratively), yet this current method serves its purpose effectively

{ a: "5" b: "6", c: "7" }

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

Exploring Three.js on Cordova with WebGL

I am working on developing a mobile app using Three.js on Cordova. While the app runs smoothly on a PC browser, it encounters an issue when trying to create the WebGL context on a Samsung Note 3 device. The specific error message is: THREE.WebGLRenderer ...

What steps can be taken to avoid special characters in ion-input fields?

When inputting special characters into the field used for storing the alphanumeric serial number, they are accepted. I need to prevent special characters from being entered in the input field. <ion-input [(ngModel)]="serial_number" (ngModelCha ...

"Implementing a Redux structure to enhance audio player functionality and effectively manage error

Imagine I am in the process of developing an audio player that includes a control panel for users to pause/play the currently selected track, along with the actual audio players. This involves actions such as pausing/playing the track, with the audio playe ...

What is the best way to split two sets of radio buttons with the same name into distinct blocks in an HTML form?

For my project, I am working with two sets of radio buttons where the values are stored in a Database. Depending on another result in the HTML form, I need to display one set of radio buttons or the other. The issue arises when using the same name for all ...

The JavaScript setTimeout function not triggering repetitively for 10 instances

I'm facing an issue with a JavaScript/jQuery function that is designed to call itself multiple times if there is no available data. This is determined by making a web service call. However, the logging inside the web service indicates that it is only ...

Using Express to Deliver Static Content to Subdirectories

I am currently using Express to serve a React application that was bootstrapped with Create React App. The project has the following directory structure: |--client/ | |--build/ | | |--static/ | | | |--main.css | | | |--main.js | ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

"An error occurred when trying to access a property that was not yet defined, prior

Within my child component, I am attempting to retrieve a nested property (referred to as background_color) from a state object in the store (referred to as template): <template> <div class="btn" :style="{ 'background- ...

Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below: [{ "thread_id": 2710, "parent_id": "", "username": "string", "comment": "string", "postdate": "2017-06-09T07:12:32.000Z", "id": 1 }, { "thread_id": 2710, "parent_ ...

Error: Unable to access the 'version' property of null

Having trouble installing any software on my computer, I've attempted various solutions suggested here but none have been successful. $ npm install axios npm ERR! Cannot read property '**version**' of null npm ERR! A complete log of this ru ...

Adjust the color of a contenteditable div once the value matches

I currently have a table with some contenteditable divs: <div contenteditable="true" class="change"> This particular JavaScript code is responsible for changing the color of these divs based on their content when the page loads. However, I am now ...

How to determine if an Angular list has finished rendering

I am facing an issue where I have a large array that is being loaded into a ul list using ng-repeat in Angular. The loading of the list takes too long and I want to display a loader while it's loading, but hide it only when the ul list is fully render ...

Displaying the number of tasks completed compared to the total number of tasks within a JavaScript ToDo list

Currently, I'm in the process of creating a basic ToDo list using HTML, JS, and CSS. The last task on my list is to display to the user the total number of tasks and how many have been completed. For instance, if there are 3 completed tasks out of 7 i ...

ReactJS: Oops! Looks like there's an issue with the element type - it's invalid. We were expecting a string

I am in the process of setting up a basic server-side rendered React application. Listed below are the steps I have taken: Step 1: Creating a new React app using create-react-app: npx create-react-app my-ssr-app Step 2: Installing necessary dependencies: ...

Problem with Java class in GWT JsInterop

Having some trouble with JsInterop while wrapping up a piece of JavaScript code. The JavaScript code looks like this: com = { gwidgets: {} }; com.gwidgets.Spring = function () { this.name = "hello"; }; com.gwidgets.Spring.prototype.getName = ...

Scroll through the menu with ease

I am facing an issue with my menu that has 2 levels. Whenever I try to scroll down, I want the position of the Logo to change to the bottom of the menu smoothly. However, during scrolling, there is a noticeable shake in the menu movement which makes it app ...

The Ajax page does not respond to click events when the function is declared within $(function(){ }) block

Create two functions as shown below: <script> $(function () { function myFunctionB() { alert("ddd"); } }) function myFunctionA() { alert("ddd"); } </sc ...

Sweet treats, items, and data interchange format

Can an object be converted to a string, stored in a cookie, retrieved, and then parsed back to its original form when the user logs on again? Here's a concise example of what I'm asking: var myObject = { prop1: "hello", prop2: 42 }; va ...

Leverage dynamically loaded HTML classes using jQuery

My page has dynamically loaded divs with the class name product. The issue I am facing is that Jquery does not seem to recognize this class when using the code below. Clicking on the product divs doesn't trigger any action, while clicking on nav-eleme ...

Marionette - Apply a class to the parent ItemView's tagname

I've been working with Bootstrap accordion panels and I'm trying to assign a class to the parent panel of the panel-collapse. Essentially, what I want to achieve is: if (child element) hasClass('panel-collapse.in') { this.addClass ...