vue 实现组单选
Vue 实现单选组件的核心方法
使用 v-model 绑定数据
在 Vue 中,通过 v-model 实现双向数据绑定。定义一个响应式数据(如 selectedOption)存储当前选中的值,绑定到单选组件的 value 属性。

<template>
<div>
<input
type="radio"
v-model="selectedOption"
value="option1"
id="option1"
>
<label for="option1">选项1</label>
<input
type="radio"
v-model="selectedOption"
value="option2"
id="option2"
>
<label for="option2">选项2</label>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: '' // 默认选中项
}
}
}
</script>
动态渲染选项列表
若选项数据来自后端或动态生成,可通过 v-for 遍历渲染,并绑定唯一标识(如 id)作为 value。

<template>
<div>
<div v-for="option in options" :key="option.id">
<input
type="radio"
v-model="selectedOption"
:value="option.id"
:id="`option-${option.id}`"
>
<label :for="`option-${option.id}`">{{ option.label }}</label>
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ id: 1, label: '选项A' },
{ id: 2, label: '选项B' }
]
}
}
}
</script>
自定义单选组件
封装可复用的单选组件,通过 props 接收选项列表和默认值,通过 emit 触发选中事件。
<!-- RadioGroup.vue -->
<template>
<div>
<div v-for="item in options" :key="item.value">
<input
type="radio"
:id="item.value"
:value="item.value"
v-model="internalValue"
>
<label :for="item.value">{{ item.label }}</label>
</div>
</div>
</template>
<script>
export default {
props: {
options: { type: Array, required: true },
value: { type: [String, Number], default: '' }
},
computed: {
internalValue: {
get() { return this.value },
set(val) { this.$emit('input', val) }
}
}
}
</script>
使用自定义组件
在父组件中引入并绑定数据,实现逻辑解耦。
<template>
<RadioGroup
v-model="selected"
:options="radioOptions"
/>
</template>
<script>
import RadioGroup from './RadioGroup.vue'
export default {
components: { RadioGroup },
data() {
return {
selected: 'a',
radioOptions: [
{ value: 'a', label: 'Alpha' },
{ value: 'b', label: 'Beta' }
]
}
}
}
</script>
注意事项
- 唯一标识:确保每个单选按钮的
id和value唯一,避免冲突。 - 初始值:若需默认选中,初始化时设置
selectedOption为对应选项的value。 - 样式控制:可通过 CSS 或第三方 UI 库(如 Element UI、Ant Design Vue)美化单选组。






