Django+Vue.js项目表格实现分页及搜索框跨页查询方案咨询
Vue.js 原生表格分页+全量搜索实现方案
直接基于你现有Vue2代码改造,无需引入额外第三方库,不会出现和jQuery相关的适配冲突,搜索默认对全量数据生效(跨所有分页),改造步骤如下:
1. 新增必要的响应式数据
在Vue的data配置中新增分页相关参数:
data:() => ({ filter: '', rows: book_rows, // 新增分页参数 currentPage: 1, // 默认当前第一页 pageSize: 20, // 每页显示条数,可根据需求调整 })
2. 调整计算属性,拆分过滤和分页逻辑
保留原有的全量过滤逻辑,新增分页后的数据计算属性:
computed: { // 原全量过滤逻辑不变,搜索对所有数据生效 filteredRows() { return this.rows.filter(row => { const author = String(row.author).toString().toLowerCase(); const title = String(row.title).toLowerCase(); const searchTerm = this.filter.toLowerCase(); return title.includes(searchTerm) || author.includes(searchTerm); }); }, // 新增:对过滤后的数据做分页切片 paginatedRows() { const start = (this.currentPage - 1) * this.pageSize; const end = start + this.pageSize; return this.filteredRows.slice(start, end); }, // 新增:计算总页数 totalPages() { return Math.ceil(this.filteredRows.length / this.pageSize); } }, // 新增:监听搜索关键词变化,自动跳回第一页,避免页码超出总页数 watch: { filter() { this.currentPage = 1; } }
3. 修改表格遍历数据源
把表格tbody的v-for从filteredRows改成paginatedRows:
<tr v-for="(row, index) in paginatedRows" :key="`title-${index}`"> <!-- 原有单元格内容不变 --> </tr>
4. 新增分页控件(放在表格下方、底部按钮上方即可)
<!-- 分页区域 --> <div class="pagination" style="margin: 10px 0; display: flex; gap: 10px; align-items: center;"> <button type="button" @click="currentPage -= 1" :disabled="currentPage === 1" >上一页</button> <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span> <span>共 {{ filteredRows.length }} 条数据</span> <button type="button" @click="currentPage += 1" :disabled="currentPage === totalPages" >下一页</button> </div>
效果说明
- 初始化仅渲染第一页的20条数据,页面加载速度大幅提升,底部按钮可正常显示
- 搜索时先对全量700+条数据做匹配,再对匹配结果做分页,保证搜索跨所有分页生效
- 完全基于Vue原生能力实现,无第三方依赖冲突,不会触发重复加载
内容的提问来源于stack exchange,提问作者Django
相关产品推荐
相关产品推荐

