vue实现div单选
实现 div 单选功能
在 Vue 中实现 div 单选功能可以通过多种方式完成。以下是几种常见的实现方法:
使用 v-model 和计算属性
通过 v-model 绑定一个变量,结合计算属性实现单选效果:
<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: 'Option A' },
{ value: 'B', label: 'Option B' },
{ value: 'C', label: 'Option C' }
]
}
}
}
</script>
<style>
.active {
background-color: #42b983;
color: white;
}
</style>
使用组件封装
创建一个可复用的单选组件:
<template>
<div class="radio-group">
<div
v-for="item in items"
:key="item.value"
class="radio-item"
:class="{ 'selected': value === item.value }"
@click="$emit('input', item.value)"
>
{{ item.label }}
</div>
</div>
</template>
<script>
export default {
props: {
value: {
type: [String, Number],
required: true
},
items: {
type: Array,
required: true
}
}
}
</script>
<style>
.radio-item {
padding: 8px 16px;
cursor: pointer;
border: 1px solid #ddd;
margin: 4px;
}
.selected {
background-color: #42b983;
color: white;
}
</style>
使用 v-for 和动态样式
通过 v-for 循环渲染选项,动态应用样式:
<template>
<div>
<div
v-for="(item, index) in items"
:key="index"
class="option"
:class="{ active: activeIndex === index }"
@click="selectItem(index)"
>
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeIndex: null,
items: ['Option 1', 'Option 2', 'Option 3']
}
},
methods: {
selectItem(index) {
this.activeIndex = index
}
}
}
</script>
<style>
.option {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
cursor: pointer;
}
.active {
background-color: #42b983;
color: white;
}
</style>
使用 Vuex 管理状态
在大型应用中,可以使用 Vuex 管理单选状态:
<template>
<div>
<div
v-for="option in options"
:key="option.value"
@click="selectOption(option.value)"
:class="{ 'active': $store.state.selectedOption === option.value }"
>
{{ option.label }}
</div>
</div>
</template>
<script>
export default {
computed: {
options() {
return [
{ value: 'A', label: 'Option A' },
{ value: 'B', label: 'Option B' },
{ value: 'C', label: 'Option C' }
]
}
},
methods: {
selectOption(value) {
this.$store.commit('setSelectedOption', value)
}
}
}
</script>
使用动态组件
通过动态组件实现更复杂的选择逻辑:
<template>
<div>
<div
v-for="option in options"
:key="option.component"
@click="currentComponent = option.component"
:class="{ 'active': currentComponent === option.component }"
>
{{ option.label }}
</div>
<component :is="currentComponent" />
</div>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: {
ComponentA,
ComponentB
},
data() {
return {
currentComponent: null,
options: [
{ component: 'ComponentA', label: 'Show A' },
{ component: 'ComponentB', label: 'Show B' }
]
}
}
}
</script>
以上方法都可以实现 div 单选功能,选择哪种方式取决于具体项目需求和复杂度。简单的单选可以使用第一种方法,复杂的项目可能需要组件封装或状态管理。







