vue 点击实现单选
实现 Vue 单选点击功能
在 Vue 中实现单选功能可以通过多种方式完成,以下是几种常见的方法:
方法一:使用 v-model 绑定
通过 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>
.active {
background-color: #eee;
}
</style>
方法二:使用 radio input
利用原生 radio input 元素实现单选:
<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="radio"
v-model="selected"
:value="option.value"
>
{{ option.label }}
</label>
</div>
</template>
<script>
export default {
data() {
return {
selected: null,
options: [
{ value: 'A', label: '选项A' },
{ value: 'B', label: '选项B' },
{ value: 'C', label: '选项C' }
]
}
}
}
</script>
方法三:使用组件封装
创建一个可复用的单选组件:
<!-- RadioGroup.vue -->
<template>
<div class="radio-group">
<div
v-for="option in options"
:key="option.value"
class="radio-option"
:class="{ active: modelValue === option.value }"
@click="$emit('update:modelValue', option.value)"
>
{{ option.label }}
</div>
</div>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: true
},
modelValue: {
type: [String, Number],
default: null
}
},
emits: ['update:modelValue']
}
</script>
使用组件
<template>
<RadioGroup
v-model="selected"
:options="options"
/>
</template>
<script>
import RadioGroup from './RadioGroup.vue'
export default {
components: { RadioGroup },
data() {
return {
selected: null,
options: [
{ value: 'A', label: '选项A' },
{ value: 'B', label: '选项B' },
{ value: 'C', label: '选项C' }
]
}
}
}
</script>
注意事项
- 确保每个选项有唯一的
value值 - 使用
v-model可以简化双向绑定逻辑 - 如果需要自定义样式,可以通过 CSS 类控制选中状态
- 在组件化实现中,使用
modelValue和update:modelValue符合 Vue 3 的约定
以上方法都可以实现点击单选功能,根据项目需求选择合适的方式。组件化方法更适合在多个地方复用单选逻辑。







