Toggle is-active css classes on navigation tabs

2019-02-19 02:11发布

I'm pretty new to Vue so I'm building a test project to try it out. I have some tabs:

<div class="tabs">
      <ul>
           <li class="is-active"><a> first tab </a></li>
           <li><a> second tab </a></li>
           <li><a> third tab</a></li>
      </ul>
</div>

now, using Vue I want to have a method that removes the is-active class from all lis and set is-active to the li clicked.

I've dabbled a bit but I can't find any straightforward ways to go about it. I see that Vue has good solutions for conditional rendering but I need to fix this part first.

Where should I be looking, and how are problems like these usually solved in Vue? Do you just loop through all children of ul to remove the class, then set is-active based on the index of the li?

标签: vue.js vuejs2
1条回答
Evening l夕情丶
2楼-- · 2019-02-19 02:34

There are a dozen ways you can do this.

Here is a quick one.

console.clear()

new Vue({
  el: "#app",
  data:{
    activeTab: 1
  }
})
.is-active {
  color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<div id="app">
  <div class="tabs">
    <ul>
      <li :class="{'is-active': activeTab === 1}" @click="activeTab = 1"><a> first tab </a></li>
      <li :class="{'is-active': activeTab === 2}" @click="activeTab = 2"><a> second tab </a></li>
      <li :class="{'is-active': activeTab === 3}" @click="activeTab = 3"><a> third tab</a></li>
    </ul>
  </div>
</div>

Vue is data driven. You typically want to drive the HTML based on data. Here, class is driven by the activeTab, and activeTab is set by clicking list elements.

At some point, your tabs are likely to be data instead of hardcoded. Then your code ends up looking something like this.

console.clear()

const tabs = [{text: "first tab"}, {text: "second tab"}, {text: "third tab"}]

new Vue({
  el: "#app",
  data:{
    activeTab: tabs[0],
    tabs
  }
})
.is-active {
  color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<div id="app">
  <div class="tabs">
    <ul>
      <li v-for="tab in tabs"
          :class="{'is-active': activeTab === tab}"
          @click="activeTab = tab">
        <a>{{tab.text}}</a>
      </li>
    </ul>
  </div>
</div>

And so forth. This is how this kind of thing is accomplished with Vue.

查看更多
登录 后发表回答