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 遍历数据:
<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: {{ selectedOption }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ value: 'apple', label: 'Apple' },
{ value: 'banana', label: 'Banana' },
{ value: 'orange', label: 'Orange' }
]
}
}
}
</script>
封装可复用的单选组件
将单选按钮组封装为独立组件,提高复用性:
<!-- RadioGroup.vue -->
<template>
<div>
<label v-for="option in options" :key="option.value">
<input
type="radio"
v-model="internalValue"
:value="option.value"
@change="$emit('update:modelValue', internalValue)"
/>
{{ option.label }}
</label>
</div>
</template>
<script>
export default {
props: {
modelValue: String,
options: Array
},
data() {
return {
internalValue: this.modelValue
}
},
watch: {
modelValue(newVal) {
this.internalValue = newVal
}
}
}
</script>
使用封装后的组件
在父组件中调用:
<template>
<div>
<RadioGroup
v-model="selectedFruit"
:options="fruitOptions"
/>
<p>Selected Fruit: {{ selectedFruit }}</p>
</div>
</template>
<script>
import RadioGroup from './RadioGroup.vue'
export default {
components: { RadioGroup },
data() {
return {
selectedFruit: '',
fruitOptions: [
{ value: 'apple', label: 'Apple' },
{ value: 'banana', label: 'Banana' }
]
}
}
}
</script>
添加样式和自定义事件
通过 CSS 和事件监听增强交互性:
<template>
<div class="radio-group">
<label
v-for="option in options"
:key="option.value"
:class="{ 'active': selectedOption === option.value }"
>
<input
type="radio"
v-model="selectedOption"
:value="option.value"
@change="handleChange"
/>
{{ option.label }}
</label>
</div>
</template>
<script>
export default {
props: ['options'],
data() {
return {
selectedOption: ''
}
},
methods: {
handleChange() {
this.$emit('selected', this.selectedOption)
}
}
}
</script>
<style>
.radio-group label {
padding: 8px 12px;
border: 1px solid #ddd;
cursor: pointer;
}
.radio-group label.active {
background-color: #e0f7fa;
border-color: #4dd0e1;
}
</style>






