filter routes by a prop in the meta. Vue.js

Asked

Viewed 144 times

1

I have a prop in the goal of some routes called "displayname", I wanted to play all routes that had this prop in a navbar.. I have tried but unsuccessfully, so far I can pull all routes to the Nav component, and using the v-for I assemble the links in the navbar, but that way all my routes appear, and I just want some specifics... follow an example route with this prop and what I’ve done so far:

Route:

export const routes = [
  { path: '/', component: Home, name: 'Home', 
    meta: {
       displayName: 'Home' 
    }
  } 
];

Function that picks up the routes in the Nav component:

computed: {
  routes(){
    return this.$router.options.routes
  }
},

And v-for creates the links inside the Nav:

<router-link v-for="(r, index) in routes" :key="index" class="links" :to="r">{{ r.name }}</router-link>

The idea is to only have route links with prop displayname, and use the value of this prop in the link display.

Thank you for your attention.

1 answer

1


Before iterating over the routes, run a filter in the route array. So you can have an array only with the routes you want. In the computed, do:

computed: {
    routes() {
      return this.$router.options.routes.filter(route => "meta" in route && "displayName" in route.meta)
    }
}

The operator in checks if a property belongs to a given object. In the first comparison, we check whether the object meta exists on the route analyzed, since this is not a mandatory property of a route in Vue. Later, if the object meta exists, we check if this property displayName.

Already to create the menu, just iterate over this new array:

<router-link v-for="(route, index) in routes" :key="index" class="links" :to="route.path">{{ route.meta.displayName }}</router-link>
  • it worked mt well, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.