vue搜索过后实现分页
实现Vue搜索与分页功能
在Vue中实现搜索后分页功能需要结合数据过滤和分页逻辑。以下是具体实现方法:
数据准备与搜索过滤
创建计算属性处理搜索过滤后的数据:
computed: {
filteredItems() {
return this.items.filter(item => {
return item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
})
}
}
searchQuery是绑定到搜索输入框的v-model变量,items是原始数据数组。

分页逻辑实现
添加分页相关数据:
data() {
return {
currentPage: 1,
itemsPerPage: 10
}
}
创建分页后的数据计算属性:

computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.filteredItems.slice(start, end)
},
totalPages() {
return Math.ceil(this.filteredItems.length / this.itemsPerPage)
}
}
模板部分实现
搜索框和分页控件模板:
<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>
搜索后重置页码
添加watch确保搜索后重置页码:
watch: {
searchQuery() {
this.currentPage = 1
}
}
完整组件示例
export default {
data() {
return {
items: [], // 从API获取或本地数据
searchQuery: '',
currentPage: 1,
itemsPerPage: 10
}
},
computed: {
filteredItems() {
return this.items.filter(item => {
return item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
})
},
paginatedItems() {
const start = (this.currentPage - 1) * this.itemsPerPage
const end = start + this.itemsPerPage
return this.filteredItems.slice(start, end)
},
totalPages() {
return Math.ceil(this.filteredItems.length / this.itemsPerPage)
}
},
watch: {
searchQuery() {
this.currentPage = 1
}
}
}
这种方法实现了搜索过滤与分页的完整功能,当用户搜索时会自动过滤数据并重置到第一页,分页控件会根据过滤后的数据量动态更新。






