vue实现单选增加class
实现方法
在Vue中实现单选增加class可以通过多种方式完成,以下是几种常见的方法:
使用v-bind:class绑定动态class
通过绑定一个对象到v-bind:class,根据条件动态切换class。例如,当选中某个选项时,为其添加active类:
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
:class="{ active: selectedIndex === index }"
@click="selectedIndex = index"
>
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['选项1', '选项2', '选项3'],
selectedIndex: -1
}
}
}
</script>
<style>
.active {
background-color: #f0f0f0;
}
</style>
使用计算属性

如果需要更复杂的逻辑,可以使用计算属性返回class对象:
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
:class="getClass(index)"
@click="selectedIndex = index"
>
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['选项1', '选项2', '选项3'],
selectedIndex: -1
}
},
methods: {
getClass(index) {
return {
active: this.selectedIndex === index,
'other-class': this.selectedIndex === index && someOtherCondition
}
}
}
}
</script>
使用数组语法

如果需要同时应用多个class,可以使用数组语法:
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
:class="['base-class', { active: selectedIndex === index }]"
@click="selectedIndex = index"
>
{{ item }}
</div>
</div>
</template>
使用事件处理器
在事件处理器中直接操作DOM元素的classList:
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
ref="items"
@click="selectItem(index)"
>
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['选项1', '选项2', '选项3'],
selectedIndex: -1
}
},
methods: {
selectItem(index) {
if (this.selectedIndex >= 0) {
this.$refs.items[this.selectedIndex].classList.remove('active')
}
this.$refs.items[index].classList.add('active')
this.selectedIndex = index
}
}
}
</script>
注意事项
- 使用
v-bind:class是Vue推荐的方式,因为它更符合Vue的响应式特性。 - 避免直接操作DOM,除非有特殊需求。
- 如果class逻辑复杂,考虑使用计算属性或方法返回class对象。
- 确保key的唯一性,避免使用index作为key,如果列表可能变化。






