vue实现div单选
实现思路
在Vue中实现div单选功能,可以通过数据绑定和事件处理完成。核心是维护一个选中状态变量,通过点击事件更新该变量,并利用动态类名或样式控制选中效果。
基础实现代码示例
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="selectedId = item.id"
:class="{ 'active': selectedId === item.id }"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedId: null,
items: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
]
}
}
}
</script>
<style>
.active {
background-color: #409EFF;
color: white;
}
</style>
使用计算属性优化
对于更复杂的选择逻辑,可以使用计算属性:
<template>
<div>
<div
v-for="item in items"
:key="item.id"
@click="selectItem(item)"
:class="getItemClass(item)"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedItem: null,
items: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
]
}
},
methods: {
selectItem(item) {
this.selectedItem = item
}
},
computed: {
getItemClass() {
return (item) => ({
'active': this.selectedItem?.id === item.id
})
}
}
}
</script>
封装为可复用组件
可以封装为独立组件提高复用性:

<!-- RadioDivGroup.vue -->
<template>
<div class="radio-div-group">
<slot :selected="selectedValue" :select="selectValue"></slot>
</div>
</template>
<script>
export default {
props: {
value: { type: [String, Number, Object], default: null }
},
data() {
return {
selectedValue: this.value
}
},
methods: {
selectValue(val) {
this.selectedValue = val
this.$emit('input', val)
this.$emit('change', val)
}
},
watch: {
value(newVal) {
this.selectedValue = newVal
}
}
}
</script>
使用封装组件
<template>
<radio-div-group v-model="selectedId">
<template #default="{ selected, select }">
<div
v-for="item in items"
:key="item.id"
@click="select(item.id)"
:class="{ 'active': selected === item.id }"
>
{{ item.text }}
</div>
</template>
</radio-div-group>
</template>
<script>
import RadioDivGroup from './RadioDivGroup.vue'
export default {
components: { RadioDivGroup },
data() {
return {
selectedId: 1,
items: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
]
}
}
}
</script>
注意事项
- 确保每个选项有唯一标识符(id)
- 使用v-model可以实现双向绑定
- 样式处理推荐使用CSS类而不是内联样式
- 对于大量数据,考虑性能优化(如虚拟滚动)






