zerostatic
zerostatic

Reputation: 112

vuejs, how to bind dynamic class within a v-for loop

In Vuejs, I would like to set an "active" class on my nav. The nav is built in a v-for loop like this:

<li v-for="item in arrNav" v-bind:class="{'active' : item.id }">
    <a v-link="{ path: item.id }">{{ item.title}}</a>
</li>

here's the data:

arrNav: [{
    'title': 'Home',
    'id': 'home'
  },
  {
    'title': 'About',
    'id': 'about'
  },
  {
    'title': 'Contact',
    'id': 'contact'
  }]

This is setting an "active" class on every li. I assume this is because item.id is returning true because it's a string. Is there a way to evaluate item.id to its variable name?

Upvotes: 4

Views: 2685

Answers (1)

user900362
user900362

Reputation:

There's a more elegant to do it, as vue-router provides this functionality by default. If you want to give a class to the parent item of the navigation element, you can use v-link-active:

<li v-for="item in arrNav" v-link-active>
    <a v-link="{ path: item.id }">{{ item.title}}</a>
</li>

That will give the li item a v-link-active class. Take a look at this page on the vue-router documentation.

Upvotes: 3

Related Questions