javascripthtmlvue.jsvuejs2dynamic-class

Vue.js dynamic classes


I have some html using Vue.js here:

<div id="app">
  <ul class="navbar-nav">
      <li class="nav-item" v-for="tab in tabs">
          <a href="#" class="nav-link">{{ tab.name }}</a>
      </li>
  </ul>
</div>

I have the javascript here:

var app = new Vue({
  el: '#app',
  data: {
      tabs: [
        { name: "Home", active: "" },
        { name: "Challenges", active: "active" },
        { name: "Scoreboard", active: "" },
        { name: "About", active: "" }
    ]
  }
});

I want to set class to tabs.active since I'm using bootstrap. How can I do that?


Solution

  • Add

     v-bind:class="tab.active"
    

    So your code should look like this:

    var app = new Vue({
      el: '#app',
      data: {
        tabs: [{
            name: "Home",
            active: ""
          },
          {
            name: "Challenges",
            active: "active"
          },
          {
            name: "Scoreboard",
            active: ""
          },
          {
            name: "About",
            active: ""
          }
        ]
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <ul class="navbar-nav">
        <li class="nav-item" v-for="tab in tabs" v-bind:class="tab.active">
          <a href="#" class="nav-link">{{ tab.name }}</a>
        </li>
      </ul>
    </div>