【问题标题】:Setting an active state with Vue JS and for loop使用 Vue JS 和 for 循环设置活动状态
【发布时间】:2017-12-29 16:56:52
【问题描述】:

我在 Vue 中有一个字符串列表,我正在使用 v-for 通过 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' }
})

【问题讨论】:

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


    【解决方案1】:

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

    在您的视图模型定义中添加:

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

    修改模板中的 a 标签:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 2019-01-11
    • 1970-01-01
    相关资源
    最近更新 更多