Dipak Telangre
Dipak Telangre

Reputation: 1993

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 ??

Upvotes: 0

Views: 494

Answers (2)

kissu
kissu

Reputation: 46754

Supposing the following router configuration

/src/router/index.js

import Vue from "vue";
import VueRouter from "vue-router";
import CustomersName from "../views/CustomersName.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/customers/:name",
    name: "customers-name",
    component: CustomersName,
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

export default router;

And the following view

/src/views/CustomersName.vue

<template>
  <div>
    <p>Current route's customer name: {{ $route.params.name }}</p>
    <p>
      Do we have either Sam or Alice currently?
      {{ ["Sam", "Alice"].includes($route.params.name) }}
    </p>

    <router-link
      class="block"
      :to="{ name: 'customers-name', params: { name: 'Sam' } }"
    >
      visit Sam
    </router-link>
    <router-link
      class="block"
      :to="{ name: 'customers-name', params: { name: 'Bob' } }"
    >
      visit Bob
    </router-link>
    <router-link
      class="block"
      :to="{ name: 'customers-name', params: { name: 'Alice' } }"
    >
      visit Alice
    </router-link>
    <router-link
      class="block"
      :to="{ name: 'customers-name', params: { name: 'alice' } }"
    >
      visit small alice
    </router-link>
  </div>
</template>

<style scoped>
.block {
  display: block;
}
</style>

We will have the following result

enter image description here

Here is a video on how it actually looks

enter image description here

Upvotes: 0

Naren
Naren

Reputation: 4480

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

Upvotes: 0

Related Questions