使用Vue JS和for循环设置活动状态

时间:2017-07-24 07:48:27

标签: javascript jquery html twitter-bootstrap vue.js

我在Vue中有一个字符串列表,我使用v-for列出所有这些字符串在" list-group"用Bootstrap。我想设置"活跃"点击其中一个项目的状态,但我找不到使用for循环识别列表中特定项目的方法。

HTML -

<div class="list-group" id="ServersList">
<a href="#" class="list-group-item" v-for="Server in Servers">{{Server.text}}</a>
</div> 

VueJS -

var ServersList = new Vue({
    el: '#ServersList',
    data: {
        Servers: [
            { text: '1' },
            { text: '2' },
            { text: '3' },
            { text: '4' },
            { text: '5' },
            { text: '6' }
})

1 个答案:

答案 0 :(得分:2)

您可以使用v-for="(Server, index) in Servers"。 Index将存储每个元素的当前索引。有了这个,你就可以像这样调用一个定义的方法:

在viewmodel定义中添加:

data: {
  currentIndex: 0
},
methods: {
  myClick(index) {
    this.currentIndex = index
  }
}

修改模板中的标签:

<a href="#" 
  v-for="(server, index) in Servers" 
  :class="{yourActiveClass: currentIndex === index, yourInactiveClass: currentIndex !== index}" 
  @click="myClick(index)">
相关问题