vue实现题目翻页
实现思路
在Vue中实现题目翻页功能,通常需要结合分页逻辑和组件状态管理。核心是通过当前页码控制题目数据的显示,并提供翻页按钮切换页码。
基础实现方案
数据准备
- 准备题目数组,每个元素代表一道题目
- 定义当前页码的响应式数据
data() {
return {
questions: [
{id: 1, title: "题目1", content: "内容1"},
{id: 2, title: "题目2", content: "内容2"},
// 更多题目...
],
currentPage: 1,
pageSize: 1 // 每页显示1题
}
}
计算当前题目 使用计算属性获取当前页对应的题目:
computed: {
currentQuestion() {
const start = (this.currentPage - 1) * this.pageSize
return this.questions.slice(start, start + this.pageSize)[0]
}
}
翻页方法 实现上一页和下一页方法:
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
}
},
computed: {
totalPages() {
return Math.ceil(this.questions.length / this.pageSize)
}
}
模板部分
<template>
<div class="question-container">
<div v-if="currentQuestion">
<h3>{{ currentQuestion.title }}</h3>
<p>{{ currentQuestion.content }}</p>
</div>
<div class="pagination">
<button
@click="prevPage"
:disabled="currentPage === 1">
上一题
</button>
<span>第 {{ currentPage }} 题 / 共 {{ totalPages }} 题</span>
<button
@click="nextPage"
:disabled="currentPage === totalPages">
下一题
</button>
</div>
</div>
</template>
进阶优化
添加过渡效果 可以为题目切换添加过渡动画:
<transition name="fade" mode="out-in">
<div v-if="currentQuestion" :key="currentQuestion.id">
<!-- 题目内容 -->
</div>
</transition>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
保存答题状态 使用对象记录每道题的答题状态:
data() {
return {
answers: {}
}
},
methods: {
saveAnswer(answer) {
this.$set(this.answers, this.currentQuestion.id, answer)
}
}
完整组件示例
<template>
<div>
<transition name="fade" mode="out-in">
<div v-if="currentQuestion" :key="currentQuestion.id">
<h3>{{ currentQuestion.title }}</h3>
<p>{{ currentQuestion.content }}</p>
<textarea
v-model="answers[currentQuestion.id]"
placeholder="输入答案">
</textarea>
</div>
</transition>
<div class="nav-buttons">
<button @click="prevPage" :disabled="currentPage === 1">上一题</button>
<span>{{ currentPage }}/{{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一题</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
questions: [], // 可通过API获取
currentPage: 1,
pageSize: 1,
answers: {}
}
},
computed: {
currentQuestion() {
const start = (this.currentPage - 1) * this.pageSize
return this.questions.slice(start, start + this.pageSize)[0]
},
totalPages() {
return Math.ceil(this.questions.length / this.pageSize)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) this.currentPage--
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++
}
}
}
</script>
注意事项
- 对于大量题目考虑分页加载,不要一次性加载所有题目数据
- 移动端适配可以添加滑动翻页功能
- 考虑添加题目跳转功能,允许用户直接选择特定题号
- 对于考试场景,可以添加计时功能和自动保存答案的逻辑







