当前位置:首页 > VUE

vue搜索过后实现分页

2026-01-12 01:18:05VUE

实现 Vue 搜索后分页的方法

数据绑定与搜索逻辑

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

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

计算属性处理过滤与分页

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

vue搜索过后实现分页

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>

重置页码处理

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

vue搜索过后实现分页

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钩子中加载:

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

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

相关文章

vue实现主题

vue实现主题

Vue 实现主题的方法 使用 CSS 变量动态切换主题 定义全局 CSS 变量,通过修改这些变量实现主题切换。在 Vue 的根组件或全局样式中定义变量: :root { --primary-co…

vue实现toggle

vue实现toggle

Vue 实现 Toggle 功能 在 Vue 中实现 toggle(切换)功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 和 v-on 通过 v-model 绑定数据,结合…

vue实现购票

vue实现购票

Vue 实现购票功能 数据结构设计 购票功能通常需要以下数据结构: 场次信息(时间、地点、价格) 座位信息(可选座位、已售座位) 用户订单信息 示例数据结构: data() { retur…

vue实现编辑

vue实现编辑

Vue 实现编辑功能 在 Vue 中实现编辑功能通常涉及表单绑定、状态管理和事件处理。以下是一个常见的实现方法: 双向数据绑定 使用 v-model 指令实现表单元素与数据的双向绑定: <i…

vue 实现脚本

vue 实现脚本

Vue 实现脚本的方法 Vue.js 提供了多种方式来实现脚本功能,包括组件内脚本、混入(Mixins)、插件(Plugins)以及自定义指令等。以下是常见的实现方式: 组件内脚本 在 Vue 单…

利用vue 实现

利用vue 实现

以下是利用 Vue 实现常见功能的几种方法,分为不同场景和技术要点: 数据绑定与响应式更新 Vue 的核心特性是数据绑定,通过 v-model 实现双向绑定: <template>…