vue.js路由器中的可选参数


105

我需要以两种方式路由到某个组件-一种带有参数,一种不带参数。我已经搜索了可选的参数,但是却找不到很多信息。

所以我的路线:

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

当我以编程方式用参数调用它时,一切都很好

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

但是我也需要像这样通过导航

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

offers组件接受的丙

props: ['member'],

和这样使用的组件

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

现在,我设法使其工作的丑陋方法是复制路线,并使其中一个不采取支撑措施:

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

它实际上有效,但我对此不满意-也在开发模式下,vuejs警告我 [vue-router] Duplicate named routes definition: { name: "offers", path: "/offers" }

当然,有一种方法可以在组件调用中执行可选参数:member="member"

Answers:



1

此外,您还可以从调用路线的地方发送不同的参数。

<router-link
    :to="{
     name: 'ComponentName',
     params: { member: {}, otherParams: {} }
     }"
>

0

对于高级匹配模式,该手册说

vue-router使用path-to-regexp作为其路径匹配引擎,因此它支持许多高级匹配模式,例如可选动态段,零个或多个/一个或多个需求,甚至是自定义regex模式。查阅其文档以了解这些高级模式,以及在vue-router中使用它们的示例。

到正则表达式的页面/手册=> https://github.com/pillarjs/path-to-regexp/tree/v1.7.0#parameters

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.