vue实现div单选
Vue实现Div单选的方法
使用v-model和v-for
通过v-model绑定选中的值,结合v-for循环渲染选项,利用CSS类动态切换选中样式。
<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: 1, label: '选项1' },
{ value: 2, label: '选项2' },
{ value: 3, label: '选项3' }
]
}
}
}
</script>
<style>
.active {
background-color: #409EFF;
color: white;
}
</style>
使用计算属性
通过计算属性处理选中状态,适合需要复杂逻辑的场景。
<template>
<div>
<div
v-for="option in options"
:key="option.value"
@click="toggleSelect(option.value)"
:class="getClass(option.value)"
>
{{ option.label }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
selected: null,
options: [
{ value: 'a', label: '选项A' },
{ value: 'b', label: '选项B' }
]
}
},
methods: {
toggleSelect(value) {
this.selected = value
}
},
computed: {
getClass() {
return (value) => ({
'active': this.selected === value
})
}
}
}
</script>
使用组件化方式
将单选逻辑封装为可复用组件,通过props传递选项和默认值。
<!-- RadioDiv.vue -->
<template>
<div class="radio-group">
<div
v-for="item in options"
:key="item.value"
@click="$emit('update:modelValue', item.value)"
:class="{ 'selected': modelValue === item.value }"
>
{{ item.label }}
</div>
</div>
</template>
<script>
export default {
props: {
options: Array,
modelValue: [String, Number]
},
emits: ['update:modelValue']
}
</script>
<!-- 使用示例 -->
<template>
<RadioDiv
v-model="selectedOption"
:options="[
{ value: 'x', label: '选项X' },
{ value: 'y', label: '选项Y' }
]"
/>
</template>
使用Vuex状态管理
当需要在多个组件间共享选中状态时,可以采用Vuex管理。
// store.js
export default new Vuex.Store({
state: {
selectedDiv: null
},
mutations: {
setSelectedDiv(state, value) {
state.selectedDiv = value
}
}
})
// 组件中使用
<template>
<div @click="$store.commit('setSelectedDiv', 'div1')"
:class="{ active: $store.state.selectedDiv === 'div1' }">
选项1
</div>
</template>
注意事项
- 确保每个选项有唯一标识value
- 样式处理建议使用transition添加动画效果
- 移动端可添加:active伪类提升点击反馈
- 复杂场景可结合Vue的自定义指令实现







