vue分页前台实现
Vue 分页前台实现方法
基础分页组件实现
创建一个基础的Pagination.vue组件,接收当前页码和总页数作为props:
<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: page === currentPage }"
>{{ page }}</button>
</span>
<button
@click="changePage(currentPage + 1)"
:disabled="currentPage === totalPages"
>下一页</button>
</div>
</template>
<script>
export default {
props: {
currentPage: {
type: Number,
required: true
},
totalPages: {
type: Number,
required: true
}
},
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>
使用分页组件
在父组件中使用分页组件,并处理分页逻辑:
<template>
<div>
<!-- 显示分页数据 -->
<ul>
<li v-for="item in paginatedData" :key="item.id">
{{ item.name }}
</li>
</ul>
<!-- 分页组件 -->
<Pagination
:current-page="currentPage"
:total-pages="totalPages"
@page-changed="onPageChange"
/>
</div>
</template>
<script>
import Pagination from './Pagination.vue';
export default {
components: {
Pagination
},
data() {
return {
allData: [], // 所有数据
currentPage: 1,
itemsPerPage: 10
};
},
computed: {
totalPages() {
return Math.ceil(this.allData.length / this.itemsPerPage);
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.allData.slice(start, end);
}
},
methods: {
onPageChange(page) {
this.currentPage = page;
}
},
async created() {
// 获取数据
this.allData = await fetchData(); // 替换为实际的数据获取方法
}
};
</script>
高级分页功能
对于大量数据的分页显示,可以添加页码省略功能:
computed: {
pages() {
const range = [];
const maxVisible = 5; // 最多显示的页码数
let start = 1;
let end = this.totalPages;
if (this.totalPages > maxVisible) {
start = Math.max(this.currentPage - Math.floor(maxVisible / 2), 1);
end = start + maxVisible - 1;
if (end > this.totalPages) {
end = this.totalPages;
start = end - maxVisible + 1;
}
}
for (let i = start; i <= end; i++) {
range.push(i);
}
return range;
}
}
样式优化
添加基础样式使分页组件更美观:
.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;
}
与后端API集成
当需要从后端获取分页数据时:
methods: {
async fetchPaginatedData(page) {
try {
const response = await axios.get('/api/items', {
params: {
page,
per_page: this.itemsPerPage
}
});
this.paginatedData = response.data.items;
this.totalPages = response.data.total_pages;
} catch (error) {
console.error('获取数据失败:', error);
}
},
onPageChange(page) {
this.currentPage = page;
this.fetchPaginatedData(page);
}
}
这些方法提供了从基础到高级的Vue分页实现方案,可以根据实际需求进行调整和扩展。







