vue组件实现单选按钮
实现单选按钮的基本结构
在Vue中实现单选按钮,可以使用原生HTML的<input type="radio">结合v-model实现数据双向绑定。以下是一个基础示例:
<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: {{ selectedOption }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: ''
}
}
}
</script>
动态渲染单选按钮组
通过v-for动态生成单选按钮选项,适用于选项数据来自API或需要灵活配置的场景:
<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="radio"
v-model="selectedOption"
:value="option.value"
>
{{ option.label }}
</label>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ value: 'apple', label: 'Apple' },
{ value: 'banana', label: 'Banana' },
{ value: 'orange', label: 'Orange' }
]
}
}
}
</script>
自定义单选按钮组件
封装可复用的单选按钮组件,增强样式控制和功能扩展:
<!-- RadioButton.vue -->
<template>
<label class="radio-container">
<input
type="radio"
:checked="isChecked"
@change="$emit('change', value)"
>
<span class="radio-checkmark"></span>
<span class="radio-label">{{ label }}</span>
</label>
</template>
<script>
export default {
props: {
label: String,
value: [String, Number],
isChecked: Boolean
}
}
</script>
<style>
.radio-container {
display: block;
position: relative;
padding-left: 25px;
cursor: pointer;
}
.radio-checkmark {
position: absolute;
top: 0;
left: 0;
height: 16px;
width: 16px;
border: 1px solid #ddd;
border-radius: 50%;
}
.radio-container input:checked ~ .radio-checkmark {
background-color: #2196F3;
}
</style>
单选按钮组管理
使用计算属性和watch处理复杂逻辑,例如表单验证或联动操作:
<template>
<div>
<RadioButton
v-for="option in options"
:key="option.value"
:label="option.label"
:value="option.value"
:is-checked="selectedOption === option.value"
@change="handleChange"
/>
</div>
</template>
<script>
import RadioButton from './RadioButton.vue'
export default {
components: { RadioButton },
data() {
return {
selectedOption: null,
options: [
{ value: 1, label: 'Low' },
{ value: 2, label: 'Medium' },
{ value: 3, label: 'High' }
]
}
},
methods: {
handleChange(value) {
this.selectedOption = value
this.$emit('input', value)
}
}
}
</script>
表单集成与验证
在Vue表单中配合验证库(如VeeValidate)使用单选按钮:
<template>
<form @submit.prevent="submitForm">
<div v-for="option in options" :key="option.value">
<input
type="radio"
v-model="form.level"
:value="option.value"
v-validate="'required'"
name="level"
>
{{ option.label }}
</div>
<span v-show="errors.has('level')" class="error">
{{ errors.first('level') }}
</span>
<button type="submit">Submit</button>
</form>
</template>
<script>
export default {
data() {
return {
form: { level: '' },
options: [
{ value: 'basic', label: 'Basic' },
{ value: 'pro', label: 'Professional' }
]
}
},
methods: {
submitForm() {
this.$validator.validate().then(valid => {
if (valid) {
// 提交表单逻辑
}
})
}
}
}
</script>






