Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vue.js - Optional param in vuejs router

I need to route to a certain component in two ways - one with a param, one without. I have searched for optional params and somehow can't find much info.

So my route:

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

When I call it with the param programmatically, all is fine

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

However I also need to call it via nav like this

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

The offers component accepts the prop

props: ['member'],

And component used as such

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

Now the ugly way I've managed to get it working is duplicating the route and making one of them not take props:

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

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

Surely there's a way to do optional param in the component call :member="member" ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just adding a question mark ? will make it optional.

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

It works for Vue Router 2.0 onward.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...