vue搜索分页实现
Vue 搜索分页实现
基本思路
在Vue中实现搜索分页功能,通常需要结合后端API接口,前端处理搜索关键词、分页参数以及数据渲染。以下是实现的核心步骤和代码示例。
数据准备
定义组件的数据结构,包括搜索关键词、分页参数、列表数据等。
data() {
return {
searchQuery: '', // 搜索关键词
currentPage: 1, // 当前页码
pageSize: 10, // 每页显示条数
total: 0, // 总数据量
list: [], // 列表数据
loading: false // 加载状态
}
}
搜索方法
封装搜索请求方法,调用后端API并处理返回结果。

methods: {
async fetchData() {
this.loading = true;
try {
const params = {
keyword: this.searchQuery,
page: this.currentPage,
size: this.pageSize
};
const res = await api.getList(params); // 假设api是封装好的请求方法
this.list = res.data.list;
this.total = res.data.total;
} catch (error) {
console.error('搜索失败:', error);
} finally {
this.loading = false;
}
}
}
分页组件
使用Element UI或其他UI库的分页组件,绑定分页参数和事件。
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="total, prev, pager, next, jumper">
</el-pagination>
事件处理
处理分页切换和搜索事件,触发数据重新加载。

methods: {
handlePageChange(page) {
this.currentPage = page;
this.fetchData();
},
handleSearch() {
this.currentPage = 1; // 搜索时重置页码
this.fetchData();
}
}
防抖优化
为避免频繁触发搜索请求,可以为搜索输入框添加防抖功能。
import { debounce } from 'lodash';
methods: {
handleSearch: debounce(function() {
this.currentPage = 1;
this.fetchData();
}, 500)
}
完整示例
以下是一个完整的Vue组件示例:
<template>
<div>
<el-input v-model="searchQuery" placeholder="请输入关键词" @input="handleSearch"></el-input>
<el-table :data="list" v-loading="loading">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@current-change="handlePageChange"
:current-page="currentPage"
:page-size="pageSize"
:total="total"
layout="total, prev, pager, next, jumper">
</el-pagination>
</div>
</template>
<script>
import { debounce } from 'lodash';
export default {
data() {
return {
searchQuery: '',
currentPage: 1,
pageSize: 10,
total: 0,
list: [],
loading: false
}
},
methods: {
handlePageChange(page) {
this.currentPage = page;
this.fetchData();
},
handleSearch: debounce(function() {
this.currentPage = 1;
this.fetchData();
}, 500),
async fetchData() {
this.loading = true;
try {
const params = {
keyword: this.searchQuery,
page: this.currentPage,
size: this.pageSize
};
const res = await api.getList(params);
this.list = res.data.list;
this.total = res.data.total;
} catch (error) {
console.error('搜索失败:', error);
} finally {
this.loading = false;
}
}
},
mounted() {
this.fetchData();
}
}
</script>
注意事项
- 确保后端API支持关键词搜索和分页参数。
- 分页组件的
total属性需要与后端返回的总数据量一致。 - 加载状态
loading可以提升用户体验,避免重复请求。






