vue搜索过后实现分页
实现 Vue 搜索后分页的方法
数据绑定与搜索逻辑
在 Vue 组件中定义数据属性,包括原始数据列表、搜索关键词、分页相关参数:
data() {
return {
originalList: [], // 原始数据
filteredList: [], // 过滤后的数据
searchQuery: '', // 搜索关键词
currentPage: 1, // 当前页码
itemsPerPage: 10 // 每页显示数量
}
}
计算属性处理过滤与分页
使用计算属性实现搜索过滤和分页逻辑:
computed: {
filteredItems() {
return this.originalList.filter(item => {
return item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
})
},
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
return this.filteredItems.slice(start, start + this.itemsPerPage)
},
totalPages() {
return Math.ceil(this.filteredItems.length / this.itemsPerPage)
}
}
模板部分实现
在模板中绑定搜索输入和分页控件:
<template>
<div>
<input v-model="searchQuery" placeholder="搜索...">
<ul>
<li v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</li>
</ul>
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1">
上一页
</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button
@click="currentPage++"
:disabled="currentPage >= totalPages">
下一页
</button>
</div>
</div>
</template>
重置页码处理
当搜索条件变化时,需要重置当前页码到第一页:
watch: {
searchQuery() {
this.currentPage = 1
}
}
样式优化
添加基础样式提升用户体验:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
异步数据加载
如果数据需要从API获取,可以在created或mounted钩子中加载:
async created() {
const response = await fetch('/api/items')
this.originalList = await response.json()
}






