我如何切换单个 <li> 的类?元素? [英] How do I toggle the classes of individual <li> elements?
问题描述
当我在下面的代码中切换变量 active
时,active
CSS 类会从列表中的所有元素中应用/删除.如何单独定位列表元素?Todo-List 示例具有类似的功能(已完成 todo/todo),但它有点超出我的技能范围.
When I toggle my variable active
in the code below, the active
CSS class is applied/removed from all elements in the list. How do I target the list elements individually? The Todo-List example has similar functionality (with todo / todo completed), but it's a bit beyond my skill set.
<ul>
<li v-bind:class="{ active: active }" v-on:click="toggleActive">Test 1</li>
<li v-bind:class="{ active: active }" v-on:click="toggleActive">Test 2</li>
<li v-bind:class="{ active: active }" v-on:click="toggleActive">Test 3</li>
</ul>
toggleActive: function() {
this.active = !this.active;
}
推荐答案
一种方法是将每个状态存储在一个 item
对象中.因此,您需要创建一个 items
数组,并且每个 item
都具有以下结构:
One way to do it is to store each state inside an item
object. So you would need to create an array of items
, and each item
would have the structure:
{
text: "item #"
active: true
}
注意我在调用 toggleActive
方法时传递了项目引用.
Note I'm passing the item reference when calling the toggleActive
method.
<li v-for="item in items"
v-bind:class="{ active: item.active }"
v-on:click="toggleActive(item)">
{{ item.text }}
</li>
toggleActive: function(item) {
item.active = !item.active;
console.log(item);
}
这里有一个工作示例:https://jsfiddle.net/pkwroL5L/1/
希望能帮到你!
这篇关于我如何切换单个 <li> 的类?元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!