vue实现单选增加class
Vue 实现单选增加 class
在 Vue 中实现单选并动态添加 class,可以通过绑定 v-bind:class 和 v-on:click 来实现。以下是一个常见的实现方式:
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="selectItem(item.id)"
:class="{ 'active': selectedItem === item.id }"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
],
selectedItem: null
}
},
methods: {
selectItem(id) {
this.selectedItem = id
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用计算属性优化
如果需要更复杂的逻辑,可以使用计算属性来动态生成 class:
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="selectItem(item.id)"
:class="getClass(item.id)"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
],
selectedItem: null
}
},
methods: {
selectItem(id) {
this.selectedItem = id
}
},
computed: {
getClass() {
return (id) => ({
'active': this.selectedItem === id,
'disabled': this.selectedItem !== null && this.selectedItem !== id
})
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
.disabled {
opacity: 0.5;
}
</style>
使用组件实现复用
如果需要在多个地方复用单选逻辑,可以将其封装为组件:
<template>
<div>
<radio-group v-model="selectedItem" :options="items" />
</div>
</template>
<script>
import RadioGroup from './RadioGroup.vue'
export default {
components: {
RadioGroup
},
data() {
return {
items: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
],
selectedItem: null
}
}
}
</script>
RadioGroup.vue 组件:
<template>
<div>
<div
v-for="item in options"
:key="item.id"
@click="$emit('update:modelValue', item.id)"
:class="{ 'active': modelValue === item.id }"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: true
},
modelValue: {
type: [Number, String],
default: null
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>






