Vue3 题库答题界面开发示例:前端代码实现
<template>
<div class='question-container'>
<div class='question-header'>
<h1>{{ currentQuestion.question }}</h1>
<h2>第 {{ currentIndex + 1 }} 题,共 {{ totalQuestions }} 题</h2>
</div>
<div class='question-content'>
<ul>
<li v-for='(option, index) in currentQuestion.options' :key='index'>
<label>
<input type='radio' :name='`option-${currentIndex}`' :value='option' v-model='selectedOption'>
{{ option }}
</label>
</li>
</ul>
</div>
<div class='question-footer'>
<button @click='submitAnswer'>提交答案</button>
</div>
</div>
</template>
<script>
import { ref, reactive } from 'vue'
export default {
name: 'Question',
setup() {
// 题目列表
const questions = ref([])
// 当前题目的索引
const currentIndex = ref(0)
// 当前题目
const currentQuestion = ref({})
// 总共的题目数
const totalQuestions = ref(0)
// 答案选项
const selectedOption = ref('')
// 答案列表
const answers = reactive([])
// 获取题目列表
const fetchQuestions = async () => {
const response = await fetch('/api/questions')
const data = await response.json()
questions.value = data.questions
totalQuestions.value = data.totalQuestions
currentQuestion.value = questions.value[currentIndex.value]
}
// 提交答案
const submitAnswer = () => {
answers[currentIndex.value] = selectedOption.value
if (currentIndex.value < totalQuestions.value - 1) {
currentIndex.value++
currentQuestion.value = questions.value[currentIndex.value]
selectedOption.value = ''
} else {
// 所有题目已经回答完毕,提交答案到后端进行处理
submitAnswersToBackend()
}
}
// 提交答案到后端进行处理
const submitAnswersToBackend = async () => {
const response = await fetch('/api/answers', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ answers })
})
const result = await response.json()
console.log(result)
}
fetchQuestions()
return {
currentIndex,
currentQuestion,
totalQuestions,
selectedOption,
submitAnswer
}
}
}
</script>
原文地址: https://www.cveoy.top/t/topic/oMrp 著作权归作者所有。请勿转载和采集!