Using the same view component with different route, but with different props

Viewed 297

I have a view component, ViewDeal, that I want to reuse for different routes /housedeal/1 and /cardeal/1.

I'm using Vue Router and it's working nice, except I must know in the view component what route was used.

So this is my component:

const ViewDeal = {
  props: ['id'],
  template: '<div>Is this a car deal view or a house deal view? What route was used?</div>'
}

And in vue router I have this:

const router = new VueRouter({
  routes: [
    { path: '/housedeal/:id', component: ViewDeal, props: true },
    { path: '/cardeal/:id', component: ViewDeal, props: true },
  ]
})

I read about Object mode in Vue Router which means I can add a prop to housedeal route eg. {isHousedeal: true}, but then the :id param wont be passed in.

This thread didn't have any answers to combine url props with object ones.

1 Answers

This should work :

const router = new VueRouter({
  routes: [
    { path: '/housedeal/:id', component: ViewDeal, props: {isHousedeal: true} },
    { path: '/cardeal/:id', component: ViewDeal, props: {isHousedeal: false} },
  ]
})

Then to retrieve the id, you can use {{ $route.params.id }} in your component.

const ViewDeal = {
  props: ['isHousedeal'],
  template: '<div>Is this house deal? {{isHousedeal}}. ID : {{$route.params.id}}</div>'
}
Related