vue实现分页搜索功能
实现分页搜索功能
在Vue中实现分页搜索功能通常需要结合前端分页逻辑和后端API(或模拟数据)。以下是一个完整的实现方案:
基础数据准备
创建Vue组件时定义必要的数据属性:
data() {
return {
searchQuery: '',
currentPage: 1,
itemsPerPage: 10,
allItems: [], // 原始数据
filteredItems: [], // 筛选后的数据
totalPages: 0
}
}
计算属性处理
通过计算属性实现实时筛选和分页计算:
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.filteredItems.slice(start, end)
}
}
搜索筛选方法
实现搜索筛选逻辑:

methods: {
filterItems() {
if (!this.searchQuery) {
this.filteredItems = [...this.allItems]
} else {
const query = this.searchQuery.toLowerCase()
this.filteredItems = this.allItems.filter(item =>
Object.values(item).some(val =>
String(val).toLowerCase().includes(query)
)
)
}
this.currentPage = 1
this.totalPages = Math.ceil(this.filteredItems.length / this.itemsPerPage)
}
}
生命周期钩子
在mounted钩子中初始化数据:
mounted() {
// 实际项目中这里可能是API调用
fetch('/api/items')
.then(res => res.json())
.then(data => {
this.allItems = data
this.filterItems()
})
}
模板部分
模板中实现搜索框和分页控制:

<template>
<div>
<input
v-model="searchQuery"
@input="filterItems"
placeholder="搜索..."
/>
<table>
<tr v-for="item in paginatedItems" :key="item.id">
<!-- 表格内容 -->
</tr>
</table>
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1"
>
上一页
</button>
<span>第 {{ currentPage }} 页/共 {{ totalPages }} 页</span>
<button
@click="currentPage++"
:disabled="currentPage >= totalPages"
>
下一页
</button>
</div>
</div>
</template>
样式优化
添加基本样式增强用户体验:
.pagination {
margin-top: 20px;
display: flex;
align-items: center;
gap: 10px;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
后端API整合方案
若需连接真实后端API,修改filterItems方法:
async filterItems() {
const params = {
query: this.searchQuery,
page: this.currentPage,
limit: this.itemsPerPage
}
const res = await axios.get('/api/items', { params })
this.filteredItems = res.data.items
this.totalPages = res.data.totalPages
}
性能优化建议
对于大数据量情况考虑以下优化:
- 添加防抖处理搜索输入
- 实现虚拟滚动替代完整列表渲染
- 添加加载状态指示器
以上方案可根据实际项目需求进行调整,核心逻辑是将搜索、筛选和分页功能有机结合,通过Vue的响应式系统实现动态更新。






