vue实现搜索分页
实现搜索分页的步骤
创建Vue组件
在Vue项目中创建一个组件,包含搜索框和分页控件。确保组件有data属性存储搜索关键词和分页信息。
<template>
<div>
<input v-model="searchQuery" placeholder="Search..." @input="handleSearch" />
<table>
<tr v-for="item in paginatedData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
<div class="pagination">
<button @click="prevPage" :disabled="currentPage === 1">Previous</button>
<span>Page {{ currentPage }} of {{ totalPages }}</span>
<button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
</div>
</div>
</template>
设置初始数据
在组件的data中定义初始状态,包括搜索关键词、当前页数和每页显示数量。
data() {
return {
searchQuery: '',
allData: [], // 从API获取的原始数据
filteredData: [], // 过滤后的数据
currentPage: 1,
itemsPerPage: 10
}
}
实现搜索功能
添加一个方法来处理搜索逻辑,过滤数据并重置当前页数。
methods: {
handleSearch() {
this.filteredData = this.allData.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
);
this.currentPage = 1;
}
}
计算分页数据
使用计算属性来获取当前页的数据和总页数。
computed: {
totalPages() {
return Math.ceil(this.filteredData.length / this.itemsPerPage);
},
paginatedData() {
const start = (this.currentPage - 1) * this.itemsPerPage;
const end = start + this.itemsPerPage;
return this.filteredData.slice(start, end);
}
}
添加分页导航
实现翻页方法,确保页数在有效范围内。
methods: {
nextPage() {
if (this.currentPage < this.totalPages) {
this.currentPage++;
}
},
prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
}
}
}
获取初始数据
在mounted钩子中获取初始数据,并初始化过滤后的数据。
mounted() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
this.allData = data;
this.filteredData = data;
});
}
样式调整
为分页控件添加基本样式,确保用户界面友好。

.pagination {
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
}
注意事项
- 确保搜索功能对大小写不敏感,提升用户体验。
- 分页控件应禁用不可用的按钮,避免无效操作。
- 考虑添加加载状态,在数据获取时显示提示信息。






