vue实现搜索分页
Vue 实现搜索分页
数据绑定与搜索逻辑
在 Vue 中实现搜索分页功能,需要将搜索关键词与分页参数绑定到数据模型中。通常使用 v-model 绑定搜索输入框,分页参数(如 currentPage 和 pageSize)可通过计算属性或直接绑定。
<template>
<div>
<input v-model="searchQuery" placeholder="搜索关键词" @input="handleSearch" />
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<span>{{ currentPage }} / {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
</div>
</template>
计算分页数据
通过计算属性过滤搜索数据并分页。使用 filter 方法根据搜索关键词筛选数据,再通过 slice 方法实现分页。
<script>
export default {
data() {
return {
searchQuery: '',
currentPage: 1,
pageSize: 10,
allData: [] // 原始数据
};
},
computed: {
filteredData() {
return this.allData.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
);
},
totalPages() {
return Math.ceil(this.filteredData.length / this.pageSize);
},
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.filteredData.slice(start, end);
}
},
methods: {
handleSearch() {
this.currentPage = 1; // 搜索时重置到第一页
},
prevPage() {
if (this.currentPage > 1) this.currentPage--;
},
nextPage() {
if (this.currentPage < this.totalPages) this.currentPage++;
}
}
};
</script>
后端分页与 API 集成
如果数据量较大,建议将分页和搜索逻辑交给后端处理。通过 API 传递搜索关键词和分页参数,后端返回分页后的数据。
methods: {
async fetchData() {
const params = {
query: this.searchQuery,
page: this.currentPage,
size: this.pageSize
};
const response = await axios.get('/api/data', { params });
this.paginatedData = response.data.items;
this.totalPages = response.data.totalPages;
},
handleSearch() {
this.currentPage = 1;
this.fetchData();
}
}
使用分页组件库
对于更复杂的分页需求,可以集成第三方分页组件(如 element-ui 或 ant-design-vue),直接绑定分页事件和参数。
<template>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="filteredData.length"
layout="prev, pager, next">
</el-pagination>
</template>
性能优化
对于前端分页,当数据量较大时,可使用虚拟滚动(如 vue-virtual-scroller)减少 DOM 渲染压力。对于后端分页,确保 API 响应速度,合理设置缓存策略。







