vue分页查询怎么实现
vue分页查询实现方法
使用Element UI的分页组件
安装Element UI库并引入Pagination组件:
npm install element-ui
在Vue文件中引入并使用:
<template>
<div>
<el-table :data="tableData">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 50]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [],
currentPage: 1,
pageSize: 10,
total: 0
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val
this.fetchData()
},
handleCurrentChange(val) {
this.currentPage = val
this.fetchData()
},
fetchData() {
axios.get('/api/data', {
params: {
page: this.currentPage,
size: this.pageSize
}
}).then(response => {
this.tableData = response.data.list
this.total = response.data.total
})
}
},
created() {
this.fetchData()
}
}
</script>
自定义分页实现
不使用UI库时,可以手动实现分页功能:
<template>
<div>
<table>
<!-- 表格内容 -->
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
data: [],
currentPage: 1,
pageSize: 10,
totalItems: 0
}
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.pageSize)
},
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++
}
},
fetchData() {
// 获取数据逻辑
}
}
}
</script>
后端API配合
确保后端API支持分页参数:
// Express示例
app.get('/api/data', (req, res) => {
const page = parseInt(req.query.page) || 1
const size = parseInt(req.query.size) || 10
const offset = (page - 1) * size
// 查询数据库
db.query('SELECT * FROM table LIMIT ? OFFSET ?', [size, offset])
.then(results => {
db.query('SELECT COUNT(*) as total FROM table')
.then(countResult => {
res.json({
list: results,
total: countResult[0].total,
page,
size
})
})
})
})
分页优化建议
使用防抖技术减少频繁请求:
methods: {
fetchData: _.debounce(function() {
// 请求逻辑
}, 300)
}
添加加载状态提升用户体验:
<template>
<el-pagination v-loading="loading" ... />
</template>
<script>
export default {
data() {
return {
loading: false
}
},
methods: {
fetchData() {
this.loading = true
axios.get(...).finally(() => {
this.loading = false
})
}
}
}
</script>
分页样式定制
通过CSS自定义分页样式:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
}
.pagination button {
margin: 0 10px;
padding: 5px 10px;
background: #409EFF;
color: white;
border: none;
border-radius: 3px;
}
.pagination button:disabled {
background: #ccc;
cursor: not-allowed;
}






