使用具有不同路由但具有不同道具的相同视图组件
Using the same view component with different route, but with different props
我有一个视图组件 ViewDeal,我想将其重复用于不同的路由 /housedeal/1
和 /cardeal/1
。
我正在使用 Vue Router,它工作得很好,除了我必须在视图组件中知道使用了什么路由。
所以这是我的组件:
const ViewDeal = {
props: ['id'],
template: '<div>Is this a car deal view or a house deal view? What route was used?</div>'
}
在 vue 路由器中我有这个:
const router = new VueRouter({
routes: [
{ path: '/housedeal/:id', component: ViewDeal, props: true },
{ path: '/cardeal/:id', component: ViewDeal, props: true },
]
})
我在 Vue Router 中读到 Object mode,这意味着我可以向 housedeal 路由添加一个道具,例如。 {isHousedeal: true}
,但是 :id
参数不会被传入。
This thread 没有任何答案可以将 url 道具与对象道具结合起来。
这应该有效:
const router = new VueRouter({
routes: [
{ path: '/housedeal/:id', component: ViewDeal, props: {isHousedeal: true} },
{ path: '/cardeal/:id', component: ViewDeal, props: {isHousedeal: false} },
]
})
然后要检索 ID,您可以在组件中使用 {{ $route.params.id }}
。
const ViewDeal = {
props: ['isHousedeal'],
template: '<div>Is this house deal? {{isHousedeal}}. ID : {{$route.params.id}}</div>'
}
我有一个视图组件 ViewDeal,我想将其重复用于不同的路由 /housedeal/1
和 /cardeal/1
。
我正在使用 Vue Router,它工作得很好,除了我必须在视图组件中知道使用了什么路由。
所以这是我的组件:
const ViewDeal = {
props: ['id'],
template: '<div>Is this a car deal view or a house deal view? What route was used?</div>'
}
在 vue 路由器中我有这个:
const router = new VueRouter({
routes: [
{ path: '/housedeal/:id', component: ViewDeal, props: true },
{ path: '/cardeal/:id', component: ViewDeal, props: true },
]
})
我在 Vue Router 中读到 Object mode,这意味着我可以向 housedeal 路由添加一个道具,例如。 {isHousedeal: true}
,但是 :id
参数不会被传入。
This thread 没有任何答案可以将 url 道具与对象道具结合起来。
这应该有效:
const router = new VueRouter({
routes: [
{ path: '/housedeal/:id', component: ViewDeal, props: {isHousedeal: true} },
{ path: '/cardeal/:id', component: ViewDeal, props: {isHousedeal: false} },
]
})
然后要检索 ID,您可以在组件中使用 {{ $route.params.id }}
。
const ViewDeal = {
props: ['isHousedeal'],
template: '<div>Is this house deal? {{isHousedeal}}. ID : {{$route.params.id}}</div>'
}