vue搜索过后实现分页
Vue 实现搜索后分页功能
数据绑定与搜索逻辑
在 Vue 组件中定义必要的数据属性:
data() {
return {
searchQuery: '',
currentPage: 1,
itemsPerPage: 10,
allItems: [], // 原始数据
filteredItems: [] // 搜索结果
}
}
实现搜索方法:
methods: {
performSearch() {
this.filteredItems = this.allItems.filter(item =>
item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
)
this.currentPage = 1 // 搜索后重置页码
}
}
计算属性处理分页
创建计算属性计算分页数据:
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" @input="performSearch" placeholder="搜索...">
<div v-for="item in paginatedItems" :key="item.id">
{{ item.name }}
</div>
<div class="pagination">
<button
@click="currentPage--"
:disabled="currentPage === 1"
>上一页</button>
<span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
<button
@click="currentPage++"
:disabled="currentPage >= totalPages"
>下一页</button>
</div>
样式优化
添加基础样式改善用户体验:
.pagination {
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
高级实现方案
对于大型数据集考虑使用服务器端分页:
async fetchPaginatedData() {
const response = await axios.get('/api/items', {
params: {
search: this.searchQuery,
page: this.currentPage,
limit: this.itemsPerPage
}
})
this.paginatedItems = response.data.items
this.totalItems = response.data.total
}
使用第三方库
考虑使用成熟的分页组件如 vuejs-paginate:
import Paginate from 'vuejs-paginate-next'
export default {
components: { Paginate }
}
模板中使用:
<paginate
v-model="currentPage"
:page-count="totalPages"
:click-handler="fetchPaginatedData"
:prev-text="'<'"
:next-text="'>'"
>
</paginate>






