vue.jsvuejs2vue-router

VueJs route match params only from list (Validate params value)


The route should be resolved only for the given params list (Validate params)

e.g. valid names ["Sam", "Alice"]

//route 
{
  path: "/customers/:names"  
}

// expectation 

path = /customers/Sam   => matched 
path = /customers/Alice => matched 
path = /customers/XYZ   => Not matched 
path = /customers/ABC   => Not matched 

How this can be achieved ??


Solution

  • You can use router guards to validate the route.

    Use either Global guards or In-component guards. Choose as per your requirements.

    
    // define route with valid names 
    {
        path: "/customers/:name",
        meta: {
            validNames: ["Sam", "Alice"]
        }
    }
    
    // Global Gaurd
    
    router.beforeEach((to, from, next) => {
        if (to.meta?.validNames) {
            if (!to.meta.validNames.includes(to.params.name)) {
                return ‘/error’
            }
            // else valid name
        }
        next()
    }) 
    
    

    Answering from mobile. Excuse me if there’s any typos