当前位置:首页 > VUE

vue搜索过后实现分页

2026-01-07 02:15:47VUE

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 }
}

模板中使用:

vue搜索过后实现分页

<paginate
  v-model="currentPage"
  :page-count="totalPages"
  :click-handler="fetchPaginatedData"
  :prev-text="'<'"
  :next-text="'>'"
>
</paginate>

标签: 分页vue
分享给朋友:

相关文章

vue实现密码框的包

vue实现密码框的包

Vue 密码框实现方案 在 Vue 中实现密码框功能,可以通过原生 HTML 结合 Vue 指令或使用第三方组件库完成。以下是几种常见方案: 原生 HTML + Vue 双向绑定 <t…

vue compile 实现

vue compile 实现

Vue 编译实现原理 Vue 的编译过程将模板字符串转换为渲染函数,主要分为解析、优化和代码生成三个阶段。 解析阶段(Parse) 将模板字符串转换为抽象语法树(AST)。Vue 使用正则表达式和有…

vue 实现排序

vue 实现排序

Vue 实现排序的方法 使用计算属性实现排序 通过计算属性对数组进行排序,可以保持原始数据不变。示例代码展示了如何对列表按名称升序排序: <template> <div>…

vue实现列表

vue实现列表

Vue 实现列表的方法 在 Vue 中实现列表渲染通常使用 v-for 指令,可以动态生成多个元素。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 遍历数组,生成列表项。v-for 需要…

vue实现书库

vue实现书库

Vue 实现书库功能 使用 Vue 构建书库功能需要结合前端框架和后端数据管理。以下是实现步骤和关键点: 项目初始化 使用 Vue CLI 或 Vite 初始化项目,安装 Vue Router 和状…

vue 轮询实现

vue 轮询实现

轮询的基本概念 轮询是一种通过定时向服务器发送请求来获取最新数据的技术。适用于需要实时更新但无法使用WebSocket的场景。 使用setInterval实现轮询 在Vue组件中,可以通过setIn…