Optional parameter in vuejs router

I need to go to a specific component in two ways: one with a parameter, without it. I was looking for optional parameters and somehow I can not find a lot of information.

So my route is:

{ path: '/offers/:member', component: Offers, name: 'offers', props: true, meta: { guest: false, needsAuth: true } }, 

When I call it with a parameter programmatically, everything is fine

 this.$router.push({ path: /offers/1234 }); 

However, I also need to call it with nav

 <router-link to="/offers">Offers</router-link> 

The offers component takes support

 props: ['member'], 

And the component used as such

 <Offers :offers="data" :member="member"></Offers> 

Now the ugly way that I managed to get it to work is to duplicate the route and that one of them does not accept props:

 { path: '/offers', component: Offers, name: 'offers', props: false, meta: { guest: false, needsAuth: true } }, 

It really works, but I'm not happy with it - also in dev mode vuejs warns me [vue-router] Duplicate named routes definition: { name: "offers", path: "/offers" }

Of course, there is a way to make an optional parameter in the component call :member="member" ?

+5
source share
1 answer

Just adding a question mark ? will make it optional.

 { path: '/offers/:member?', ... }, 

It works for Vue Router 2.0 on.

Source: https://github.com/vuejs/vue-router/issues/235#issuecomment-245447122

+10
source

Source: https://habr.com/ru/post/1274086/


All Articles