Vue.js动态类

时间:2018-12-10 02:34:52

标签: javascript html vue.js vuejs2 dynamic-class

我在这里有一些使用Vue.js的html:

<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>

我在这里有JavaScript:

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

我想将类设置为tabs.active,因为我正在使用引导程序。我该怎么办?

2 个答案:

答案 0 :(得分:2)

添加

 v-bind:class="tab.active"

因此您的代码应如下所示:

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>

答案 1 :(得分:0)

像这样使用class binding

<li class="nav-item" :class="{active: tab.active === 'active'}" v-for="tab in tabs">

new Vue({
  el: '#app',
  data: {
      tabs: [
        { name: "Home", active: "" },
        { name: "Challenges", active: "active" },
        { name: "Scoreboard", active: "" },
        { name: "About", active: "" }
    ]
  }
});
.active .nav-link {
  color: white;
  background: blue;
}
<script src="https://unpkg.com/vue@2.5.17"></script>

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