当前位置:首页 > 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中实现按钮组轮换效果可以通过动态绑定类和事件处理来完成。以下是一种常见的实现方式: 模板部分 <template> <div class="bu…

vue实现https

vue实现https

Vue 中实现 HTTPS 的步骤 在 Vue 项目中实现 HTTPS 主要涉及开发环境配置和生产环境部署。以下是具体方法: 开发环境配置(Vue CLI 或 Vite) 使用 mkcert 生成…

vue实现素材

vue实现素材

Vue 实现素材的方法 使用 Vue 组件管理素材 在 Vue 项目中,可以通过组件化的方式管理素材。创建一个专门的组件来加载和显示素材,例如图片、视频或音频文件。组件可以接收素材的路径或 URL 作…

vue 实现树状

vue 实现树状

Vue 实现树状结构的方法 递归组件实现树状结构 递归组件是 Vue 中实现树状结构的常见方法。通过组件自身调用自身,可以轻松构建多层级树状结构。 <template> <ul…

vue 实现弹窗

vue 实现弹窗

Vue 实现弹窗的方法 在 Vue 中实现弹窗功能可以通过多种方式完成,以下是几种常见的方法: 使用组件和 v-if/v-show 控制显示 创建一个独立的弹窗组件,通过 v-if 或 v-show…

vue实现伸缩

vue实现伸缩

Vue实现伸缩功能的方法 使用CSS过渡和Vue的v-if或v-show 通过CSS的transition属性结合Vue的条件渲染指令(v-if或v-show)可以实现元素的伸缩效果。定义一个CSS类…