vue实现单选答题功能
实现单选答题功能的基本思路
在Vue中实现单选答题功能,可以通过v-model绑定单选按钮组的值,结合计算属性和方法来实现答题逻辑。以下是一个完整的实现方案。
创建单选问题数据
在Vue组件的data中定义问题和选项:
data() {
return {
questions: [
{
id: 1,
text: 'Vue.js的作者是谁?',
options: [
{ id: 'a', text: '尤雨溪' },
{ id: 'b', text: 'Dan Abramov' },
{ id: 'c', text: 'Evan You' }
],
correctAnswer: 'a',
selectedAnswer: null
},
// 可以添加更多问题
],
currentQuestionIndex: 0
}
}
模板中的单选按钮组
使用v-for渲染选项,v-model绑定选中值:

<div v-for="(question, index) in questions" :key="question.id" v-show="index === currentQuestionIndex">
<h3>{{ question.text }}</h3>
<div v-for="option in question.options" :key="option.id">
<input
type="radio"
:id="`q${question.id}_${option.id}`"
:value="option.id"
v-model="question.selectedAnswer"
/>
<label :for="`q${question.id}_${option.id}`">{{ option.text }}</label>
</div>
</div>
添加导航和提交功能
<button @click="prevQuestion" :disabled="currentQuestionIndex === 0">上一题</button>
<button @click="nextQuestion" :disabled="currentQuestionIndex === questions.length - 1">下一题</button>
<button @click="submitAnswers">提交答案</button>
实现导航方法
methods: {
prevQuestion() {
if (this.currentQuestionIndex > 0) {
this.currentQuestionIndex--
}
},
nextQuestion() {
if (this.currentQuestionIndex < this.questions.length - 1) {
this.currentQuestionIndex++
}
},
submitAnswers() {
const score = this.questions.filter(
q => q.selectedAnswer === q.correctAnswer
).length
alert(`您的得分是: ${score}/${this.questions.length}`)
}
}
显示答题进度和结果
添加计算属性显示进度:
computed: {
progress() {
return ((this.currentQuestionIndex + 1) / this.questions.length * 100).toFixed(0) + '%'
},
answeredCount() {
return this.questions.filter(q => q.selectedAnswer !== null).length
}
}
在模板中添加进度显示:

<div>
进度: {{ progress }} ({{ answeredCount }}/{{ questions.length }})
</div>
添加样式反馈
可以为正确/错误答案添加样式反馈:
.correct {
background-color: #d4edda;
}
.incorrect {
background-color: #f8d7da;
}
在提交后显示结果:
submitAnswers() {
this.questions.forEach(q => {
q.isCorrect = q.selectedAnswer === q.correctAnswer
})
this.showResults = true
}
完整组件示例
export default {
data() {
return {
questions: [...], // 问题数据
currentQuestionIndex: 0,
showResults: false
}
},
computed: {
// 计算属性
},
methods: {
// 方法实现
}
}
通过以上步骤,可以在Vue中实现一个完整的单选答题功能,包括问题展示、答案选择、导航控制和结果反馈。






