vue搜索分页实现
Vue 搜索分页实现方法
基本思路
搜索分页通常需要结合后端API,前端通过Vue组件实现搜索框、分页器和数据列表的联动。核心逻辑包括:监听搜索输入变化、分页参数变化,触发数据请求并更新视图。
实现步骤
1. 组件结构设计 创建包含以下元素的Vue组件:
- 搜索输入框(使用
v-model绑定搜索关键词) - 分页器组件(可使用
el-pagination或自定义) - 数据列表展示区域
<template>
<div>
<input v-model="searchQuery" placeholder="搜索关键词"/>
<ul>
<li v-for="item in listData" :key="item.id">{{ item.name }}</li>
</ul>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total">
</el-pagination>
</div>
</template>
2. 数据状态管理
在Vue的data中定义必要变量:
data() {
return {
searchQuery: '', // 搜索词
listData: [], // 列表数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页条数
total: 0 // 总数据量
}
}
3. 核心方法实现 创建获取数据的方法,建议使用防抖优化搜索触发:
methods: {
fetchData() {
const params = {
keyword: this.searchQuery,
page: this.currentPage,
pageSize: this.pageSize
}
axios.get('/api/list', { params })
.then(res => {
this.listData = res.data.list
this.total = res.data.total
})
},
handlePageChange(page) {
this.currentPage = page
this.fetchData()
}
}
4. 监听搜索词变化
使用watch监听搜索词变化并重置页码:
watch: {
searchQuery(newVal) {
this.currentPage = 1
this.fetchData()
}
}
5. 生命周期钩子
在mounted中初始化数据:
mounted() {
this.fetchData()
}
优化建议
防抖处理 避免频繁触发搜索请求:
import { debounce } from 'lodash'
watch: {
searchQuery: debounce(function(newVal) {
this.currentPage = 1
this.fetchData()
}, 500)
}
分页器配置 根据需求调整分页器属性:
<el-pagination
background
layout="prev, pager, next"
:page-size="pageSize"
:total="total"
@current-change="handlePageChange">
</el-pagination>
空状态处理 添加数据为空时的提示:
<div v-if="listData.length === 0" class="empty-tip">
暂无数据
</div>
完整示例代码
<script>
export default {
data() {
return {
searchQuery: '',
listData: [],
currentPage: 1,
pageSize: 10,
total: 0
}
},
watch: {
searchQuery(newVal) {
this.currentPage = 1
this.fetchData()
}
},
methods: {
fetchData() {
axios.get('/api/list', {
params: {
keyword: this.searchQuery,
page: this.currentPage,
pageSize: this.pageSize
}
}).then(res => {
this.listData = res.data.list
this.total = res.data.total
})
},
handlePageChange(page) {
this.currentPage = page
this.fetchData()
}
},
mounted() {
this.fetchData()
}
}
</script>
通过以上实现,可以完成基本的搜索分页功能。根据实际项目需求,可以进一步优化UI交互或添加筛选条件等扩展功能。







