vue实现翻页效果
使用Vue实现翻页效果
在Vue中实现翻页效果通常需要结合分页组件和数据处理逻辑。以下是几种常见方法:
基础分页组件实现
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<div class="pagination">
<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 {
items: [], // 你的数据数组
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
totalPages() {
return Math.ceil(this.items.length / this.itemsPerPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.items.slice(start, end)
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
}
}
}
</script>
使用第三方分页组件
Element UI的分页组件:
<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="totalItems">
</el-pagination>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
totalItems: 100
}
},
methods: {
handleCurrentChange(val) {
this.currentPage = val
// 这里可以添加获取新页数据的逻辑
}
}
}
</script>
结合API请求的分页实现
methods: {
async fetchData() {
const response = await axios.get('/api/items', {
params: {
page: this.currentPage,
limit: this.itemsPerPage
}
})
this.items = response.data.items
this.totalItems = response.data.total
},
handlePageChange(page) {
this.currentPage = page
this.fetchData()
}
}
样式优化
可以添加CSS美化分页按钮:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
.pagination button {
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
动态调整每页显示数量
添加选择每页显示数量的功能:
<select v-model="itemsPerPage" @change="resetPage">
<option value="5">5条/页</option>
<option value="10">10条/页</option>
<option value="20">20条/页</option>
</select>
<script>
methods: {
resetPage() {
this.currentPage = 1
// 重新获取数据
}
}
</script>
以上方法可以根据实际需求组合使用,实现完整的翻页功能。对于大型项目,建议使用成熟的UI库如Element UI、Vuetify或Ant Design Vue中的分页组件。






