vue实现选题操作
Vue 实现选题操作
在 Vue 中实现选题操作通常涉及列表渲染、事件处理和状态管理。以下是一个完整的实现方案:
数据准备
定义题目列表和选中状态:
data() {
return {
questions: [
{ id: 1, text: "题目1" },
{ id: 2, text: "题目2" },
{ id: 3, text: "题目3" }
],
selectedQuestions: []
}
}
单选实现
使用复选框实现单选效果:
<div v-for="question in questions" :key="question.id">
<input
type="checkbox"
:value="question.id"
v-model="selectedQuestions"
@change="handleSingleSelect(question.id)"
>
{{ question.text }}
</div>
methods: {
handleSingleSelect(id) {
this.selectedQuestions = [id]
}
}
多选实现
直接使用 v-model 绑定多选数组:
<div v-for="question in questions" :key="question.id">
<input
type="checkbox"
:value="question.id"
v-model="selectedQuestions"
>
{{ question.text }}
</div>
全选/反选
添加全选控制按钮:
<button @click="toggleSelectAll">全选/反选</button>
methods: {
toggleSelectAll() {
if (this.selectedQuestions.length === this.questions.length) {
this.selectedQuestions = []
} else {
this.selectedQuestions = this.questions.map(q => q.id)
}
}
}
提交处理
提交选中的题目:
methods: {
submitSelection() {
console.log('已选题目ID:', this.selectedQuestions)
// 实际业务中这里可能是API调用
}
}
样式优化
使用 CSS 美化选择状态:
.question-item {
padding: 10px;
margin: 5px;
border: 1px solid #eee;
}
.question-item.selected {
background-color: #f0f8ff;
border-color: #3498db;
}
完整组件示例
<template>
<div>
<button @click="toggleSelectAll">全选/反选</button>
<div
v-for="question in questions"
:key="question.id"
class="question-item"
:class="{ selected: isSelected(question.id) }"
>
<input
type="checkbox"
:value="question.id"
v-model="selectedQuestions"
>
{{ question.text }}
</div>
<button @click="submitSelection">提交选择</button>
</div>
</template>
<script>
export default {
data() {
return {
questions: [
{ id: 1, text: "题目1" },
{ id: 2, text: "题目2" },
{ id: 3, text: "题目3" }
],
selectedQuestions: []
}
},
methods: {
isSelected(id) {
return this.selectedQuestions.includes(id)
},
toggleSelectAll() {
if (this.selectedQuestions.length === this.questions.length) {
this.selectedQuestions = []
} else {
this.selectedQuestions = this.questions.map(q => q.id)
}
},
submitSelection() {
console.log('已选题目:', this.selectedQuestions)
}
}
}
</script>
高级实现方案
对于更复杂的需求,可以考虑使用 Vuex 管理选题状态,或封装为可复用的选题组件。关键点包括:

- 支持单选/多选模式切换
- 题目分组选择
- 选择数量限制
- 题目搜索过滤
- 选择状态持久化
以上方案提供了基础的选题功能实现,可根据实际项目需求进行调整和扩展。






