【问题标题】:In Vue.js, change value of specific attribute for all items in a data array在 Vue.js 中,更改数据数组中所有项目的特定属性的值
【发布时间】:2015-08-26 05:19:37
【问题描述】:

我正在尝试在 v-repeat 中的项目列表上切换 open 类。我只希望一个列表项(最近单击的一项)具有 open 类。

输出的数据有一个“class”属性,默认情况下是一个空白字符串。我正在使用它来设置v-repeat 中的列表项的类,如下所示:

<li v-repeat="dataSet"
    v-on="click: toggleFunction(this)"
    class="{{ class }}">
    {{ itemContent }}
</li>

我在每个项目上都使用v-on="click: toggleFunction(this)",这让我可以更改特定项目的类,但是如何更改所有其他项目的类?

我目前的点击方式:

toggleFunction: function(item) {
    if (item.class == '') {
        // code to remove the `open` class from all other items should go here.
        item.class = 'open';
    } else {
        item.class = '';
    }
}

我尝试使用常规的 jQuery 函数来剥离类:确实删除了类,但它不会更改 item.class 属性,因此一旦单击项目,事情就会变得很奇怪不止一次……

我确信必须有一种直接的方法来解决这个我没有看到的问题,并且必须在数据本身中设置一个class 属性无论如何都感觉很麻烦(但我会接受任何有效的修复)。

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    我刚刚遇到了同样的问题。我仍在学习 Vue,但我使用“v-class”指令解决了它。使用 v-class,只要记录的活动值为真,它就会自动将类“open”添加到列表元素中。希望这JSFiddle 有所帮助。

    <ul>
        <li 
            v-repeat="people"
            v-on="click: toggleActive(this)"
            v-class="open: active">{{ name }}
        </li>
    </ul>
    
    
    
    
    new Vue({
        el: '#app',
        data: {
            people: [
                {name: 'mike'},
                {name: 'joe',active: true},
                {name: 'tom'},
                {name: 'mary'}
            ]
        },
        methods: {
            toggleActive: function(person) {
                // remove active from all people
                this.people.forEach(function(person){
                    person.$set('active',false);
                });
              //set active to clicked person
                person.$set('active',true);
            }
        }
    });
    

    【讨论】:

    • 这就是我要找的!你刚刚帮助了一个随机的公民!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多