vue分页的实现
Vue 分页的实现方法
使用 Element UI 的分页组件
安装 Element UI:
npm install element-ui
在 main.js 中引入:
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
在组件中使用:
<template>
<div>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 40]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
total: 100
};
},
methods: {
handleSizeChange(val) {
this.pageSize = val;
this.fetchData();
},
handleCurrentChange(val) {
this.currentPage = val;
this.fetchData();
},
fetchData() {
// 根据 currentPage 和 pageSize 获取数据
}
}
};
</script>
使用自定义分页组件
创建一个简单的自定义分页组件:
<template>
<div class="pagination">
<button
@click="changePage(currentPage - 1)"
:disabled="currentPage === 1">
上一页
</button>
<span>第 {{ currentPage }} 页</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
}
},
methods: {
changePage(page) {
this.$emit('page-changed', page);
}
}
};
</script>
<style>
.pagination {
display: flex;
justify-content: center;
gap: 10px;
}
</style>
在父组件中使用:
<template>
<div>
<!-- 数据列表 -->
<custom-pagination
:current-page="currentPage"
:total-pages="totalPages"
@page-changed="handlePageChange"
/>
</div>
</template>
<script>
import CustomPagination from './CustomPagination.vue';
export default {
components: { CustomPagination },
data() {
return {
currentPage: 1,
totalPages: 10
};
},
methods: {
handlePageChange(page) {
this.currentPage = page;
this.fetchData();
},
fetchData() {
// 获取数据逻辑
}
}
};
</script>
结合后端 API 实现分页
假设后端 API 接受 page 和 limit 参数:
methods: {
async fetchData() {
try {
const response = await axios.get('/api/data', {
params: {
page: this.currentPage,
limit: this.pageSize
}
});
this.dataList = response.data.items;
this.total = response.data.total;
} catch (error) {
console.error('获取数据失败:', error);
}
}
}
分页样式优化
添加过渡效果:
.pagination button {
transition: background-color 0.3s;
}
.pagination button:hover:not(:disabled) {
background-color: #f0f0f0;
}
禁用按钮样式:
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}






