vue 实现翻页
Vue 实现翻页功能
翻页功能通常用于数据分页展示,可以通过 Vue 结合分页逻辑实现。以下是常见的实现方法:
1. 基础数据分页
定义一个数据数组和分页参数,通过计算属性实现分页逻辑。
data() {
return {
items: [], // 所有数据
currentPage: 1, // 当前页码
itemsPerPage: 10 // 每页显示数量
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
},
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
}
}
2. 分页按钮组件
创建一个分页按钮组件,处理页码切换。
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1"
>
上一页
</button>
<span v-for="page in pages" :key="page">
<button
@click="changePage(page)"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages"
>
下一页
</button>
</div>
</template>
<script>
export default {
props: {
currentPage: Number,
totalPages: Number
},
computed: {
pages() {
const range = []
for (let i = 1; i <= this.totalPages; i++) {
range.push(i)
}
return range
}
},
methods: {
changePage(page) {
if (page >= 1 && page <= this.totalPages) {
this.$emit('page-changed', page)
}
}
}
}
</script>
3. 与后端API结合
当数据量较大时,通常需要后端分页:
methods: {
async fetchData(page = 1) {
try {
const response = await axios.get('/api/items', {
params: {
page,
per_page: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
} catch (error) {
console.error(error)
}
}
},
created() {
this.fetchData()
}
4. 使用第三方库
可以使用现成的分页组件如 vuejs-paginate:
安装:
npm install vuejs-paginate
使用:
import Paginate from 'vuejs-paginate'
export default {
components: {
Paginate
},
methods: {
changePage(page) {
this.currentPage = page
// 获取新页数据
}
}
}
<paginate
:page-count="totalPages"
:click-handler="changePage"
:prev-text="'上一页'"
:next-text="'下一页'"
:container-class="'pagination'"
>
</paginate>
5. 样式优化
为分页组件添加基础样式:
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button.active {
background: #42b983;
color: white;
border-color: #42b983;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
以上方法可以根据项目需求选择使用,前端分页适合数据量小的场景,后端分页适合大数据量情况。第三方组件可以快速实现功能,自定义组件则更灵活。







