vuejs 路由器中的可选参数 [英] 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.
所以我的路线:
{
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>
offers
组件接受 prop
props: ['member'],
和组件一样使用
<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
}
},
它确实有效,但我对它不满意 - 在开发模式下 vuejs 也在警告我 [vue-router] 重复命名路由定义:{ name: "offers", path: "/offers"}
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" }
当然有一种方法可以在组件调用 :member="member"
中做可选参数吗?
Surely there's a way to do optional param in the component call :member="member"
?
推荐答案
只需添加一个问号 ?
即可使其成为可选.
Just adding a question mark ?
will make it optional.
{
path: '/offers/:member?',
...
},
它适用于 Vue Router 2.0 以上.
It works for Vue Router 2.0 onward.
来源:https://github.com/vuejs/vue-路由器/问题/235#issuecomment-245447122
这篇关于vuejs 路由器中的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!