Search code examples
vue.jsvue-routerrouteparams

Vue.JS routing with optional parameters and in any order


I'd like to have query parameters in my Vue.JS application using vue-router like this:

http://localhost:8080/#/home/name=Alice&surname=Smith

I've added this route to my routes in the router.ts:

 routes: [{
    path: '/home/name=:name&surname=:surname',
    name: 'home',
    component: Home
 }]

What I want to do additionally is the following two things:

1) I want to be able to have the parameters name and surname in any order. E.g. these two URLs should lead to the same view:

http://localhost:8080/#/home/name=Alice&surname=Smith
http://localhost:8080/#/home/surname=Smith&name=Alice

2) I want them to be optional as well.

Is there a way to do these things? Thank you!


Solution

  • To implement what you want you have to change the route:

    routes: [{
        path: '/home',
        name: 'home',
        component: Home
    }]
    

    Open this route with query params:

    router.push({ name: 'home', query: { name: 'Alice', surname: 'Smith' }});
    

    The url will be (order of the query keys in the url doesn't matter):

    http://localhost:8080/#/home?name=Alice&surname=Smith
    

    And inside the route, you can get your query params as this.$route.query.name & this.$route.query.surname.

    Check the documentation to get more info.