vue中单选怎样实现
Vue 中实现单选的方法
使用 v-model 绑定单选按钮
通过 v-model 绑定数据,可以轻松实现单选功能。单选按钮的 value 属性决定了选中时的值。

<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>
使用 v-for 动态生成单选按钮
如果需要动态生成单选按钮,可以通过 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>
<p>选中的选项: {{ selectedOption }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: '',
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' }
]
}
}
}
</script>
使用组件封装单选逻辑
如果需要复用单选逻辑,可以封装一个自定义单选组件。
<!-- RadioGroup.vue -->
<template>
<div>
<div v-for="option in options" :key="option.value">
<input
type="radio"
:id="option.value"
:value="option.value"
v-model="internalValue"
/>
<label :for="option.value">{{ option.label }}</label>
</div>
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: ''
},
options: {
type: Array,
required: true
}
},
computed: {
internalValue: {
get() {
return this.value
},
set(newValue) {
this.$emit('input', newValue)
}
}
}
}
</script>
使用第三方库
如果需要更丰富的功能(如样式、分组等),可以使用第三方库如 element-ui 或 vant。
<template>
<div>
<el-radio v-model="selectedOption" label="option1">选项1</el-radio>
<el-radio v-model="selectedOption" label="option2">选项2</el-radio>
<p>选中的选项: {{ selectedOption }}</p>
</div>
</template>
<script>
export default {
data() {
return {
selectedOption: ''
}
}
}
</script>






