vue 实现选题操作
实现选题操作的基本思路
在Vue中实现选题操作通常涉及以下核心逻辑:维护一个数据数组存储选项,通过v-model或自定义事件绑定用户选择,动态更新选中状态。常见场景包括单选、多选、全选/反选等。
单选功能的实现
定义选项列表和当前选中项的数据:
data() {
return {
options: ['选项A', '选项B', '选项C'],
selected: null
}
}
使用v-model绑定单选按钮:
<div v-for="(option, index) in options" :key="index">
<input
type="radio"
:id="'option'+index"
:value="option"
v-model="selected"
>
<label :for="'option'+index">{{ option }}</label>
</div>
多选功能的实现
定义多选数据结构和选中状态:
data() {
return {
options: [
{ id: 1, text: '选项A', checked: false },
{ id: 2, text: '选项B', checked: false }
]
}
}
使用v-model绑定复选框:

<div v-for="option in options" :key="option.id">
<input
type="checkbox"
:id="'opt'+option.id"
v-model="option.checked"
>
<label :for="'opt'+option.id">{{ option.text }}</label>
</div>
全选/反选功能
添加计算属性处理全选逻辑:
computed: {
allChecked: {
get() {
return this.options.every(opt => opt.checked)
},
set(value) {
this.options.forEach(opt => opt.checked = value)
}
}
}
模板中添加全选复选框:
<input type="checkbox" id="selectAll" v-model="allChecked">
<label for="selectAll">全选</label>
选项组件的封装
创建可复用的选项组件:

Vue.component('check-item', {
props: ['option'],
template: `
<div>
<input
type="checkbox"
:id="'opt'+option.id"
v-model="option.checked"
>
<label :for="'opt'+option.id">{{ option.text }}</label>
</div>
`
})
父组件中使用:
<check-item
v-for="option in options"
:key="option.id"
:option="option"
@change="handleChange"
></check-item>
选中项的处理
获取当前选中项的方法:
methods: {
getSelectedItems() {
return this.options.filter(item => item.checked)
},
submitSelection() {
const selected = this.getSelectedItems()
console.log('已提交选项:', selected)
}
}
样式优化建议
添加CSS增强交互体验:
.option-item {
padding: 8px;
margin: 4px;
border-radius: 4px;
transition: background 0.3s;
}
.option-item:hover {
background: #f5f5f5;
}
.option-item.selected {
background: #e3f2fd;
}
注意事项
- 当选项数据来自异步请求时,应在数据加载完成后初始化选中状态
- 对于大量选项应考虑虚拟滚动优化性能
- 移动端适配可能需要替换原生input控件为定制组件
- 复杂选择逻辑建议使用Vuex管理状态






