vue实现ul翻页
实现 UL 列表翻页功能
在 Vue 中实现 ul 列表的翻页功能,可以通过分页逻辑和动态渲染列表实现。以下是具体实现方法:
分页数据计算
定义分页相关数据和方法,包括当前页码、每页显示数量、总数据量等:
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);
}
}
模板渲染
在模板中使用 v-for 渲染分页后的列表,并添加翻页按钮:
<ul>
<li v-for="(item, index) in paginatedItems" :key="index">
{{ item }}
</li>
</ul>
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1">
上一页
</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button
@click="currentPage++"
:disabled="currentPage >= totalPages">
下一页
</button>
</div>
样式优化
添加基础样式使翻页控件更美观:
ul {
list-style: none;
padding: 0;
}
.pagination {
margin-top: 20px;
display: flex;
align-items: center;
gap: 10px;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
完整组件示例
<template>
<div>
<ul>
<li v-for="(item, index) in paginatedItems" :key="index">
{{ item }}
</li>
</ul>
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1">
上一页
</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button
@click="currentPage++"
:disabled="currentPage >= totalPages">
下一页
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: Array.from({length: 100}, (_, i) => `项目 ${i + 1}`),
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);
}
}
};
</script>
<style>
/* 添加前面提到的样式 */
</style>
进阶优化
添加页码跳转功能:
<input
type="number"
v-model.number="inputPage"
min="1"
:max="totalPages">
<button @click="goToPage">跳转</button>
data() {
return {
inputPage: 1
};
},
methods: {
goToPage() {
if (this.inputPage >= 1 && this.inputPage <= this.totalPages) {
this.currentPage = this.inputPage;
}
}
}
使用第三方库
如果需要更复杂的分页功能,可以考虑使用分页组件库:
-
安装
vue-paginate:npm install vue-paginate -
使用示例:
import VuePaginate from 'vue-paginate'; Vue.use(VuePaginate);
methods: { changePage(pageNum) { this.currentPage = pageNum; } }







