vue项目怎么实现分页
在Vue项目中实现分页
使用Element UI的分页组件
安装Element UI后,直接使用el-pagination组件实现分页功能。
<template>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="prev, pager, next"
/>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
};
},
methods: {
handleCurrentChange(val) {
this.currentPage = val;
this.fetchData();
},
fetchData() {
// 根据currentPage和pageSize请求数据
}
}
};
</script>
手动实现简单分页
如果不依赖UI库,可以通过计算属性实现分页逻辑。
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<button @click="prevPage">上一页</button>
<button @click="nextPage">下一页</button>
</div>
</template>
<script>
export default {
data() {
return {
data: [], // 所有数据
currentPage: 1,
pageSize: 5
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.data.slice(start, end);
}
},
methods: {
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
},
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
}
}
};
</script>
结合后端API分页
通常分页数据由后端返回,前端传递页码和每页条数参数。
<script>
export default {
methods: {
async fetchData() {
const res = await axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
});
this.data = res.data.list;
this.total = res.data.total;
}
}
};
</script>
使用第三方库(如vue-paginate)
安装vue-paginate库,快速实现分页功能。
npm install vue-paginate
<template>
<paginate
:page-count="totalPages"
:click-handler="changePage"
/>
</template>
<script>
import Paginate from 'vue-paginate';
export default {
components: { Paginate },
data() {
return {
currentPage: 1,
totalPages: 10
};
},
methods: {
changePage(pageNum) {
this.currentPage = pageNum;
}
}
};
</script>






