vue 实现单选框
Vue 实现单选框的方法
在 Vue 中实现单选框可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的数据绑定功能来完成。以下是几种常见的实现方式:
使用 v-model 绑定数据
通过 v-model 将单选框的值绑定到 Vue 实例的数据属性上,实现双向数据绑定。

<template>
<div>
<label>
<input type="radio" v-model="selectedOption" value="option1">
Option 1
</label>
<label>
<input type="radio" v-model="selectedOption" value="option2">
Option 2
</label>
<p>Selected option: {{ selectedOption }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: ''
}
}
}
</script>
动态生成单选框
如果需要根据数据动态生成单选框,可以使用 v-for 指令。
<template>
<div>
<label v-for="option in options" :key="option.value">
<input type="radio" v-model="selectedOption" :value="option.value">
{{ option.label }}
</label>
<p>Selected option: {{ selectedOption }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' }
]
}
}
}
</script>
使用组件封装单选框
为了复用和更好的代码组织,可以封装一个单选框组件。

<template>
<div>
<RadioButton
v-model="selectedOption"
value="option1"
label="Option 1"
/>
<RadioButton
v-model="selectedOption"
value="option2"
label="Option 2"
/>
<p>Selected option: {{ selectedOption }}</p>
</div>
</template>
<script>
import RadioButton from './RadioButton.vue'
export default {
components: {
RadioButton
},
data() {
return {
selectedOption: ''
}
}
}
</script>
RadioButton.vue 组件的内容:
<template>
<label>
<input
type="radio"
:value="value"
:checked="modelValue === value"
@change="$emit('update:modelValue', value)"
>
{{ label }}
</label>
</template>
<script>
export default {
props: {
modelValue: {
type: String,
default: ''
},
value: {
type: String,
required: true
},
label: {
type: String,
required: true
}
}
}
</script>
处理单选框组
如果需要处理单选框组,可以将多个单选框绑定到同一个 v-model 上。
<template>
<div>
<h3>Choose a fruit:</h3>
<label>
<input type="radio" v-model="fruit" value="apple">
Apple
</label>
<label>
<input type="radio" v-model="fruit" value="banana">
Banana
</label>
<label>
<input type="radio" v-model="fruit" value="orange">
Orange
</label>
<p>Selected fruit: {{ fruit }}</p>
</div>
</template>
<script>
export default {
data() {
return {
fruit: ''
}
}
}
</script>
注意事项
- 确保每个单选框的
value属性是唯一的,避免冲突。 - 使用
v-model时,初始值应与单选框的value匹配,否则默认不会选中任何选项。 - 如果需要默认选中某个选项,可以在
data中设置初始值。
通过以上方法,可以灵活地在 Vue 中实现单选框功能。






