CamelCase
CamelCase

Reputation: 75

Can I check if my current route is in a given list of routes?

Is it possible to do this more generic?

  watch: {
    $route(to, from) {
    if(this.$route.path === '/home'){do something with id 1}
    if(this.$route.path === '/'){do it not - its not in the array}
    if(this.$route.path === '/about'){do something with id 3}
   }
  }

I ask because I dont want to have a long snake of if else conditions for every route I need to check and to avoid such stuff with maybe 50 routes like this:

I need to check if the current route is in a given list of routes and if so return an id from the array and if not return another id for not found but having problems to get the method running.

myArray: [{id: '1', path: '/home'}, {id: '3', path: '/about'}]

if(myArray.includes(this.$route.path)
return this.id
else return 666

thanks

Upvotes: 1

Views: 1743

Answers (1)

RoboKozo
RoboKozo

Reputation: 5062

You could add the data you want to act on in a meta property of each route.

https://router.vuejs.org/guide/advanced/meta.html

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      meta: { id: 1 }
    },
    {
      path: '/bar,
      component: Bar,
      meta: { id: 2 }
    }
  ]
})

Then when you watch the $route you can perform a more generic action on $route.meta.id.

Upvotes: 2

Related Questions