当前位置:首页 > VUE

vue搜索过后实现分页

2026-01-12 01:18:05VUE

实现 Vue 搜索后分页的方法

数据绑定与搜索逻辑

在 Vue 组件中定义数据属性,包括原始数据列表、搜索关键词、分页相关参数:

data() {
  return {
    originalList: [], // 原始数据
    filteredList: [], // 过滤后的数据
    searchQuery: '',  // 搜索关键词
    currentPage: 1,    // 当前页码
    itemsPerPage: 10   // 每页显示数量
  }
}

计算属性处理过滤与分页

使用计算属性实现搜索过滤和分页逻辑:

computed: {
  filteredItems() {
    return this.originalList.filter(item => {
      return item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
    })
  },
  paginatedItems() {
    const start = (this.currentPage - 1) * this.itemsPerPage
    return this.filteredItems.slice(start, start + this.itemsPerPage)
  },
  totalPages() {
    return Math.ceil(this.filteredItems.length / this.itemsPerPage)
  }
}

模板部分实现

在模板中绑定搜索输入和分页控件:

<template>
  <div>
    <input v-model="searchQuery" placeholder="搜索...">

    <ul>
      <li v-for="item in paginatedItems" :key="item.id">
        {{ item.name }}
      </li>
    </ul>

    <div class="pagination">
      <button 
        @click="currentPage--" 
        :disabled="currentPage === 1">
        上一页
      </button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button 
        @click="currentPage++" 
        :disabled="currentPage >= totalPages">
        下一页
      </button>
    </div>
  </div>
</template>

重置页码处理

当搜索条件变化时,需要重置当前页码到第一页:

watch: {
  searchQuery() {
    this.currentPage = 1
  }
}

样式优化

添加基础样式提升用户体验:

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

异步数据加载

如果数据需要从API获取,可以在created或mounted钩子中加载:

vue搜索过后实现分页

async created() {
  const response = await fetch('/api/items')
  this.originalList = await response.json()
}

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

相关文章

vue实现图库

vue实现图库

Vue 实现图库的基本方法 使用 Vue 实现图库功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用 Vue 和第三方库(如 Vue Gallery) 安装 vue-gallery 或…

vue实现高亮

vue实现高亮

Vue 实现文本高亮的方法 在 Vue 中实现文本高亮可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-html 指令 通过 v-html 指令可以动态插入 HTML 内容,将需要高…

vue实现单据

vue实现单据

Vue 实现单据功能的方法 使用 Vue 实现单据功能通常涉及表单设计、数据绑定、验证和提交等环节。以下是具体实现方案: 表单设计与数据绑定 使用 Vue 的 v-model 指令实现表单数据的双向…

vue  实现tab

vue 实现tab

实现 Tab 切换功能 在 Vue 中实现 Tab 切换功能可以通过动态组件或条件渲染完成。以下是两种常见方法: 使用 v-if 或 v-show 实现条件渲染 通过绑定 currentTab 变量…

vue实现toast

vue实现toast

Vue 实现 Toast 的方法 使用第三方库(推荐) 对于快速实现 Toast 功能,推荐使用成熟的第三方库如 vue-toastification 或 vant 的 Toast 组件。 安装 v…

vue实现双向

vue实现双向

Vue 实现双向绑定的方法 Vue 的双向绑定主要通过 v-model 指令实现,它结合了数据绑定和事件监听,适用于表单元素(如 input、select、textarea 等)。以下是几种常见的实现…