vue实现题目翻页
Vue实现题目翻页功能
使用v-for和计算属性实现分页
在Vue中可以通过计算属性对题目列表进行分页处理,结合v-for渲染当前页的题目。定义currentPage和pageSize控制分页逻辑。
data() {
return {
questions: [], // 所有题目数组
currentPage: 1,
pageSize: 10
}
},
computed: {
paginatedQuestions() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
return this.questions.slice(start, end)
},
totalPages() {
return Math.ceil(this.questions.length / this.pageSize)
}
}
模板部分实现翻页按钮
在模板中使用计算属性渲染当前页题目,并添加翻页控制按钮。通过v-for遍历paginatedQuestions显示题目,绑定翻页方法。

<div v-for="(question, index) in paginatedQuestions" :key="index">
<!-- 题目内容展示 -->
{{ question.content }}
</div>
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1">
上一页
</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button
@click="currentPage++"
:disabled="currentPage >= totalPages">
下一页
</button>
</div>
使用第三方分页组件
对于更复杂的分页需求,可以使用Element UI或Ant Design Vue等UI库的分页组件。以Element UI为例:
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="questions.length"
layout="prev, pager, next">
</el-pagination>
methods: {
handleCurrentChange(val) {
this.currentPage = val
}
}
路由参数同步分页状态

在需要保持分页状态的场景下,可以通过路由参数同步当前页码。使用Vue Router的query参数:
watch: {
currentPage(newVal) {
this.$router.push({ query: { page: newVal } })
}
},
created() {
this.currentPage = Number(this.$route.query.page) || 1
}
无限滚动加载
对于移动端或需要流畅浏览体验的场景,可以实现无限滚动加载。监听滚动事件,当接近底部时加载下一页数据:
methods: {
handleScroll() {
const bottomOfWindow =
document.documentElement.scrollTop + window.innerHeight >=
document.documentElement.offsetHeight - 100
if (bottomOfWindow && this.currentPage < this.totalPages) {
this.currentPage++
}
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}





