vue单选按钮的实现
Vue 单选按钮的实现方法
在 Vue 中实现单选按钮可以通过 v-model 绑定数据,结合原生 <input type="radio"> 或第三方组件库完成。以下是具体实现方式:
使用原生 HTML 单选按钮
通过 v-model 绑定到同一个变量,实现单选逻辑:
<template>
<div>
<input type="radio" id="option1" value="option1" v-model="selectedOption">
<label for="option1">选项1</label>
<input type="radio" id="option2" value="option2" v-model="selectedOption">
<label for="option2">选项2</label>
<input type="radio" id="option3" value="option3" v-model="selectedOption">
<label for="option3">选项3</label>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: '' // 默认选中的值
}
}
}
</script>
使用组件库(如 Element UI)
若使用 Element UI 的 el-radio 组件:
<template>
<el-radio-group v-model="selectedOption">
<el-radio label="option1">选项1</el-radio>
<el-radio label="option2">选项2</el-radio>
<el-radio label="option3">选项3</el-radio>
</el-radio-group>
</template>
<script>
export default {
data() {
return {
selectedOption: 'option1' // 默认选中第一个选项
}
}
}
</script>
动态渲染单选按钮
通过 v-for 动态生成选项:
<template>
<div>
<div v-for="option in options" :key="option.value">
<input
type="radio"
:id="option.value"
:value="option.value"
v-model="selectedOption"
>
<label :for="option.value">{{ option.label }}</label>
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: 'option1',
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' }
]
}
}
}
</script>
表单验证(Vuelidate)
结合验证库实现单选必选校验:
<template>
<form @submit.prevent="submit">
<input
type="radio"
id="agree"
value="agree"
v-model="formData.agreement"
>
<label for="agree">同意协议</label>
<span v-if="v$.formData.agreement.$error">必须选择同意</span>
<button type="submit">提交</button>
</form>
</template>
<script>
import { required } from '@vuelidate/validators'
import { useVuelidate } from '@vuelidate/core'
export default {
setup() {
return { v$: useVuelidate() }
},
data() {
return {
formData: {
agreement: ''
}
}
},
validations() {
return {
formData: {
agreement: { required }
}
}
},
methods: {
submit() {
this.v$.$validate()
if (!this.v$.$error) {
// 提交逻辑
}
}
}
}
</script>
注意事项
- 同一组的单选按钮需绑定相同的
v-model变量 - 动态生成的选项需确保
value唯一性 - 表单验证时注意处理未选中的边界情况
- 移动端适配可考虑增加点击区域(如包裹
<label>)







