我正在尝试在 v-repeat
中的项目列表中切换 open
类。我只希望一个列表项(最近单击的那个)具有 open
类。
输出的数据有一个“类”属性,默认为空字符串。我正在使用它来设置 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
属性本身感觉很老套(但我会解决对于任何有效的修复)。
最佳答案
我刚遇到同样的问题。我仍在学习 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);
}
}
});
关于javascript - 在 Vue.js 中,更改数据数组中所有项目的特定属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30765092/