vue单选按钮代码实现
基础单选按钮实现
使用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>
<p>选择的是: {{ selectedOption }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: ''
}
}
}
</script>
使用组件库实现
Element UI实现方式:
<template>
<el-radio-group v-model="radio">
<el-radio :label="1">选项A</el-radio>
<el-radio :label="2">选项B</el-radio>
</el-radio-group>
</template>
<script>
export default {
data() {
return {
radio: 1
}
}
}
</script>
动态渲染单选按钮
根据数组动态生成单选按钮:
<template>
<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>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ value: 'opt1', label: '红色' },
{ value: 'opt2', label: '蓝色' },
{ value: 'opt3', label: '绿色' }
]
}
}
}
</script>
表单验证集成
结合Vuelidate进行表单验证:
<template>
<form @submit.prevent="submit">
<div v-for="option in options" :key="option.value">
<input
type="radio"
v-model="$v.selectedOption.$model"
:value="option.value"
:id="option.value"
>
<label :for="option.value">{{ option.label }}</label>
</div>
<div v-if="$v.selectedOption.$error">必须选择一个选项</div>
<button type="submit">提交</button>
</form>
</template>
<script>
import { required } from 'vuelidate/lib/validators'
export default {
data() {
return {
selectedOption: null,
options: [
{ value: 'yes', label: '是' },
{ value: 'no', label: '否' }
]
}
},
validations: {
selectedOption: { required }
},
methods: {
submit() {
this.$v.$touch()
if (!this.$v.$invalid) {
// 提交逻辑
}
}
}
}
</script>
样式自定义
使用CSS自定义单选按钮样式:
<template>
<div class="radio-container">
<label v-for="option in options" :key="option.value" class="radio-label">
<input
type="radio"
v-model="selectedOption"
:value="option.value"
class="radio-input"
>
<span class="radio-custom"></span>
{{ option.label }}
</label>
</div>
</template>
<style>
.radio-input {
position: absolute;
opacity: 0;
}
.radio-custom {
position: relative;
display: inline-block;
width: 20px;
height: 20px;
background-color: #fff;
border: 2px solid #ccc;
border-radius: 50%;
margin-right: 10px;
}
.radio-input:checked + .radio-custom {
background-color: #42b983;
border-color: #42b983;
}
.radio-input:checked + .radio-custom::after {
content: "";
position: absolute;
width: 10px;
height: 10px;
background: white;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.radio-label {
display: flex;
align-items: center;
margin-bottom: 10px;
cursor: pointer;
}
</style>






