当前位置:首页 > VUE

vue搜索过后实现分页

2026-02-09 14:06:31VUE

实现Vue搜索与分页功能

在Vue中实现搜索后分页功能需要结合数据过滤和分页逻辑。以下是具体实现方法:

数据准备与搜索过滤

创建计算属性处理搜索过滤后的数据:

computed: {
  filteredItems() {
    return this.items.filter(item => {
      return item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
    })
  }
}

searchQuery是绑定到搜索输入框的v-model变量,items是原始数据数组。

vue搜索过后实现分页

分页逻辑实现

添加分页相关数据:

data() {
  return {
    currentPage: 1,
    itemsPerPage: 10
  }
}

创建分页后的数据计算属性:

vue搜索过后实现分页

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

搜索后重置页码

添加watch确保搜索后重置页码:

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

完整组件示例

export default {
  data() {
    return {
      items: [], // 从API获取或本地数据
      searchQuery: '',
      currentPage: 1,
      itemsPerPage: 10
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => {
        return item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      })
    },
    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)
    }
  },
  watch: {
    searchQuery() {
      this.currentPage = 1
    }
  }
}

这种方法实现了搜索过滤与分页的完整功能,当用户搜索时会自动过滤数据并重置到第一页,分页控件会根据过滤后的数据量动态更新。

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

相关文章

vue登录业务的实现

vue登录业务的实现

实现登录业务的基本流程 在Vue中实现登录业务通常涉及前端界面设计、表单验证、API请求交互、状态管理以及路由控制等环节。以下是核心实现步骤: 登录表单设计与验证 创建包含用户名和密码输入框的登录组…

vue实现xss

vue实现xss

XSS 攻击简介 XSS(跨站脚本攻击)是一种常见的安全漏洞,攻击者通过注入恶意脚本到网页中,当其他用户访问该页面时,脚本会在其浏览器中执行,可能导致数据泄露或会话劫持。 Vue 中的 XSS…

vue实现引导

vue实现引导

Vue 实现引导功能的方法 使用第三方库 推荐使用 driver.js 或 intro.js 这类专门为 Vue 设计的引导库。这些库提供了完整的 API 和样式,能够快速实现引导功能。 安装 d…

vue实现pwa

vue实现pwa

Vue 实现 PWA 的步骤 Vue 结合 PWA(Progressive Web App)可以创建离线可用的 Web 应用。以下是实现方法: 安装 Vue CLI 并创建项目 确保已安装 Vue…

轮播vue实现

轮播vue实现

使用 Vue 实现轮播功能 基础轮播实现 安装依赖(如使用 Swiper): npm install swiper vue-awesome-swiper 组件代码示例: <templat…

vue实现openoffice

vue实现openoffice

Vue 中集成 OpenOffice 的实现方法 在 Vue 项目中集成 OpenOffice 通常需要通过后端服务或现有库实现文档的预览和编辑功能。以下是几种常见的实现方式: 使用 OnlyOff…