vue实现div单选
Vue 实现 div 单选
在 Vue 中实现 div 单选可以通过 v-model 结合 v-for 和事件绑定来完成。以下是具体实现方法:
模板部分
<template>
<div>
<div
v-for="option in options"
:key="option.value"
@click="selected = option.value"
:class="{ 'active': selected === option.value }"
>
{{ option.label }}
</div>
</div>
</template>
脚本部分
<script>
export default {
data() {
return {
selected: null,
options: [
{ value: 'A', label: '选项A' },
{ value: 'B', label: '选项B' },
{ value: 'C', label: '选项C' }
]
}
}
}
</script>
样式部分
<style>
div {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
cursor: pointer;
}
.active {
background-color: #42b983;
color: white;
}
</style>
使用计算属性优化
如果需要频繁访问选中项,可以添加计算属性:
computed: {
selectedOption() {
return this.options.find(option => option.value === this.selected)
}
}
使用组件实现复用
将单选逻辑封装为可复用组件:
<template>
<div>
<div
v-for="option in options"
:key="option.value"
@click="$emit('update:modelValue', option.value)"
:class="{ 'active': modelValue === option.value }"
>
{{ option.label }}
</div>
</div>
</template>
<script>
export default {
props: {
options: Array,
modelValue: [String, Number]
},
emits: ['update:modelValue']
}
</script>
注意事项
- 确保每个选项的
value值是唯一的 - 可以通过 CSS 过渡效果增强用户体验
- 对于大量选项,考虑添加虚拟滚动优化性能







