vue实现答题测试
Vue 实现答题测试功能
数据准备
创建包含题目、选项和正确答案的数据结构,通常使用数组存储题目对象。每个题目对象包含问题文本、选项数组和正确答案索引。
data() {
return {
questions: [
{
question: "Vue 的核心特性是什么?",
options: ["组件化", "双向绑定", "虚拟DOM", "以上都是"],
answer: 3
},
{
question: "Vue 的指令是什么?",
options: ["v-if", "v-for", "v-model", "以上都是"],
answer: 3
}
],
currentQuestionIndex: 0,
selectedAnswer: null,
score: 0,
showResult: false
}
}
界面渲染
使用 Vue 的模板语法渲染题目和选项,通过 v-for 循环显示选项,使用 v-model 绑定用户选择的答案。
<template>
<div v-if="!showResult">
<h3>{{ questions[currentQuestionIndex].question }}</h3>
<div v-for="(option, index) in questions[currentQuestionIndex].options" :key="index">
<input
type="radio"
:id="'option' + index"
:value="index"
v-model="selectedAnswer"
>
<label :for="'option' + index">{{ option }}</label>
</div>
<button @click="nextQuestion">下一题</button>
</div>
<div v-else>
<h3>测试完成!你的得分是: {{ score }}/{{ questions.length }}</h3>
</div>
</template>
逻辑处理
实现题目切换和答案验证逻辑,在用户提交答案后检查是否正确并更新分数。
methods: {
nextQuestion() {
if (this.selectedAnswer === this.questions[this.currentQuestionIndex].answer) {
this.score++
}
if (this.currentQuestionIndex < this.questions.length - 1) {
this.currentQuestionIndex++
this.selectedAnswer = null
} else {
this.showResult = true
}
}
}
样式优化
添加 CSS 样式提升用户体验,如选中状态、按钮样式等。
<style>
div {
margin: 20px;
}
button {
margin-top: 10px;
padding: 8px 16px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #369b6f;
}
input[type="radio"] {
margin-right: 8px;
}
</style>
高级功能扩展
增加计时器、题目分类、进度条等增强功能。
data() {
return {
// 其他数据...
timeLeft: 30,
timer: null
}
},
mounted() {
this.startTimer()
},
methods: {
startTimer() {
this.timer = setInterval(() => {
if (this.timeLeft > 0) {
this.timeLeft--
} else {
clearInterval(this.timer)
this.nextQuestion()
}
}, 1000)
},
nextQuestion() {
clearInterval(this.timer)
// 其他逻辑...
if (!this.showResult) {
this.timeLeft = 30
this.startTimer()
}
}
}
响应式设计
使用媒体查询确保在不同设备上良好显示。
@media (max-width: 600px) {
div {
margin: 10px;
font-size: 14px;
}
button {
padding: 6px 12px;
}
}
状态管理
对于复杂应用,可以使用 Vuex 管理测试状态。
// store.js
export default new Vuex.Store({
state: {
questions: [...],
currentQuestionIndex: 0,
score: 0
},
mutations: {
NEXT_QUESTION(state) {
state.currentQuestionIndex++
},
INCREMENT_SCORE(state) {
state.score++
}
}
})






