vue实现查询分页
Vue 实现查询分页的方法
后端 API 设计
后端需要提供支持分页的 API 接口,通常包含以下参数:
page: 当前页码pageSize: 每页显示数量query: 查询条件(可选)
响应数据格式示例:

{
"data": [],
"total": 100,
"page": 1,
"pageSize": 10
}
前端组件实现
安装 axios 用于请求数据:
npm install axios
创建分页组件 Pagination.vue:

<template>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
<script>
export default {
props: {
currentPage: Number,
totalItems: Number,
pageSize: Number
},
computed: {
totalPages() {
return Math.ceil(this.totalItems / this.pageSize)
}
},
methods: {
prevPage() {
this.$emit('page-change', this.currentPage - 1)
},
nextPage() {
this.$emit('page-change', this.currentPage + 1)
}
}
}
</script>
主页面实现
在页面组件中使用分页:
<template>
<div>
<input v-model="query" placeholder="输入查询条件" @keyup.enter="search" />
<button @click="search">查询</button>
<table>
<tr v-for="item in data" :key="item.id">
<td>{{ item.name }}</td>
<!-- 其他字段 -->
</tr>
</table>
<Pagination
:current-page="pagination.page"
:total-items="pagination.total"
:page-size="pagination.pageSize"
@page-change="handlePageChange"
/>
</div>
</template>
<script>
import axios from 'axios'
import Pagination from './Pagination.vue'
export default {
components: { Pagination },
data() {
return {
query: '',
data: [],
pagination: {
page: 1,
pageSize: 10,
total: 0
}
}
},
created() {
this.fetchData()
},
methods: {
fetchData() {
const params = {
page: this.pagination.page,
pageSize: this.pagination.pageSize,
query: this.query
}
axios.get('/api/data', { params })
.then(response => {
this.data = response.data.data
this.pagination.total = response.data.total
})
},
search() {
this.pagination.page = 1
this.fetchData()
},
handlePageChange(page) {
this.pagination.page = page
this.fetchData()
}
}
}
</script>
优化建议
- 添加加载状态提示,在请求数据时显示加载动画
- 实现页码直接跳转功能
- 添加防抖处理搜索输入,避免频繁请求
- 使用 Vuex 管理分页状态(大型项目适用)
- 考虑添加 URL 参数同步,使页面状态可分享
样式处理
为分页组件添加基础样式:
.pagination {
margin-top: 20px;
display: flex;
align-items: center;
gap: 10px;
}
.pagination button {
padding: 5px 10px;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
这种方法实现了基本的查询分页功能,可以根据实际需求进行扩展和优化。






