Problem related to vue-router, i can not exclude some words from path regex

1.3k views Asked by At

I have problem related to vue-router I need to exclude some group of words like: word1, some-word2, word3... from the router path

{ 
    path: '/:pageIdenfifier(?!word1|some-word2|word3), 
    name: 'SomePage', 
    component: () => import('@/views/index'), 
    props: true, 
}

but it doesn't work - https://paths.esm.dev/?p=AAMeJbiAwBIUTHbAdgHNgAGvAjgHhxDgd4DsAYC1AEYGfCB1eFujBYAiq5kBdgSY4KMICgAA&t=/word1#

2

There are 2 answers

1
Vasile Radeanu On

As alternative, you can use beforeEnter guard for this route, like:

const blackList = ['word1','some-word2','word3']

const router = new VueRouter({
  routes: [
    {
      path: '/:pageIdenfifier',
      name: 'SomePage',
      component: () => import('@/views/index'), 
      props: true,
      beforeEnter: (to, from, next) => {
        blackList.includes(to.params.pageIdenfifier)
          ? next('/route-in-case-of-true')
          : next();
      }
    }
  ]
})

In beforeEnter just check if pageIdenfifier match some value from blackList, in case of true you should provide another route or 404 page

0
RoToRa On

I only skimmed the documentation of path-to-regexp, which is used by vue-router, but I have two guesses:

The negative look ahead in a regular expression requires round brackets, but the syntax of path-to-regexp also does, so try adding another set:

path: '/:pageIdenfifier((?!word1|some-word2|word3))', 

Using this syntax, also "gets rid of" the default regular expression, so you may need to add that back in:

path: '/:pageIdenfifier((?!word1|some-word2|word3)[^\\/]+)', 

(BTW, the string in your code is also lacking a closing quote '. Maybe it's just that.)