vue搜索过后实现分页
实现Vue搜索与分页功能
搜索功能实现
在Vue组件中定义搜索方法,通常使用v-model绑定搜索输入框的值。通过计算属性或方法过滤数据列表。
<template>
<input v-model="searchQuery" placeholder="搜索...">
</template>
<script>
export default {
data() {
return {
searchQuery: '',
allItems: [] // 原始数据
}
},
computed: {
filteredItems() {
return this.allItems.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
}
}
}
</script>
分页功能实现
基于过滤后的结果实现分页逻辑,需要计算总页数和当前页显示的数据。

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)
}
}
完整组件示例
<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
v-for="page in totalPages"
:key="page"
@click="currentPage = page"
:class="{ active: currentPage === page }"
>
{{ page }}
</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
currentPage: 1,
itemsPerPage: 10,
allItems: [
{ id: 1, name: '项目1' },
{ id: 2, name: '项目2' }
// 更多数据...
]
}
},
computed: {
filteredItems() {
return this.allItems.filter(item =>
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)
}
}
}
</script>
<style>
.pagination button.active {
font-weight: bold;
color: blue;
}
</style>
优化建议

对于大型数据集,考虑使用后端分页和搜索。前端仅处理当前页的数据,减少内存使用。
methods: {
async fetchData() {
const response = await axios.get('/api/items', {
params: {
search: this.searchQuery,
page: this.currentPage,
perPage: this.itemsPerPage
}
})
this.paginatedItems = response.data.items
this.totalPages = response.data.totalPages
}
}
注意事项
搜索和分页功能需要密切配合。搜索后应重置当前页码为1,避免显示空页。可以在搜索查询变化时添加监听:
watch: {
searchQuery() {
this.currentPage = 1
}
}






