vue查询分页前端实现
Vue 分页前端实现
基础分页组件实现
使用 Vue 的 v-for 和计算属性实现基础分页逻辑。以下是一个简单的分页组件示例:
<template>
<div>
<ul>
<li v-for="item in paginatedData" :key="item.id">{{ item.name }}</li>
</ul>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</div>
</template>
<script>
export default {
props: ['data', 'perPage'],
data() {
return {
currentPage: 1
}
},
computed: {
totalPages() {
return Math.ceil(this.data.length / this.perPage)
},
paginatedData() {
const start = (this.currentPage - 1) * this.perPage
const end = start + this.perPage
return this.data.slice(start, end)
}
},
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--
}
}
}
}
</script>
分页样式优化
添加 CSS 样式提升分页组件的视觉效果:
.pagination {
display: flex;
justify-content: center;
align-items: center;
margin-top: 20px;
gap: 10px;
}
.pagination button {
padding: 5px 10px;
border: 1px solid #ddd;
background: #fff;
cursor: pointer;
}
.pagination button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.pagination button:hover:not(:disabled) {
background: #eee;
}
完整数字分页实现
扩展基础分页,显示完整的页码列表:

<template>
<div class="pagination">
<button @click="goToPage(1)" :disabled="currentPage === 1">首页</button>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<button
v-for="page in visiblePages"
:key="page"
@click="goToPage(page)"
:class="{ active: page === currentPage }"
>
{{ page }}
</button>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
<button @click="goToPage(totalPages)" :disabled="currentPage === totalPages">尾页</button>
</div>
</template>
<script>
export default {
computed: {
visiblePages() {
const range = 2 // 显示当前页前后各2页
let start = Math.max(1, this.currentPage - range)
let end = Math.min(this.totalPages, this.currentPage + range)
if (this.currentPage - range <= 1) {
end = Math.min(2 * range + 1, this.totalPages)
}
if (this.currentPage + range >= this.totalPages) {
start = Math.max(1, this.totalPages - 2 * range)
}
const pages = []
for (let i = start; i <= end; i++) {
pages.push(i)
}
return pages
}
},
methods: {
goToPage(page) {
this.currentPage = page
}
}
}
</script>
与后端API结合
实现与后端API的分页数据请求:
methods: {
async fetchData(page = 1) {
try {
const response = await axios.get('/api/data', {
params: {
page,
per_page: this.perPage
}
})
this.data = response.data.items
this.totalItems = response.data.total
} catch (error) {
console.error('获取数据失败:', error)
}
},
goToPage(page) {
this.currentPage = page
this.fetchData(page)
}
}
使用第三方分页组件
推荐使用成熟的第三方分页组件如 vue-paginate:

-
安装:
npm install vue-paginate -
使用示例:
import VuePaginate from 'vue-paginate' Vue.use(VuePaginate)
// 模板中使用
```这些方法提供了从基础到高级的Vue分页实现方案,可根据项目需求选择合适的实现方式。






