当前位置:首页 > 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 // 搜索后重置页码
  }
}

计算属性处理分页

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

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

样式优化

添加基础样式改善用户体验:

vue搜索过后实现分页

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

模板中使用:

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

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

相关文章

vue实现选择分类

vue实现选择分类

Vue 实现选择分类的方法 使用 v-model 绑定选择值 在 Vue 中可以通过 v-model 指令实现双向数据绑定,适用于下拉选择框(<select>)。以下是一个基本示例: &…

vue如何实现放大缩小

vue如何实现放大缩小

Vue实现放大缩小功能的方法 在Vue中实现元素的放大缩小功能,可以通过CSS变换、第三方库或直接操作DOM样式来实现。以下是几种常见的方法: 使用CSS transform属性 通过绑定Vue的…

vue实现飘窗原理

vue实现飘窗原理

vue实现飘窗原理 飘窗效果通常指在页面上悬浮显示的弹窗或通知,跟随页面滚动或固定在某个位置。Vue实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组…

vue的艾特功能实现

vue的艾特功能实现

Vue 的 @ 功能实现 在 Vue 中实现类似社交平台的 @ 功能,通常涉及输入框的监听、用户匹配和选择插入。以下是具体实现方法: 监听输入框内容 使用 v-model 绑定输入框内容,并通过…

vue实现3d宇宙

vue实现3d宇宙

Vue实现3D宇宙效果 使用Three.js库 Three.js是一个强大的JavaScript 3D库,可以轻松集成到Vue项目中。安装Three.js依赖: npm install three…

vue调用接口实现退出

vue调用接口实现退出

实现Vue退出功能的步骤 在Vue中调用接口实现退出功能通常需要与后端API交互,以下是实现方法: 前端实现 创建退出方法,调用后端API接口: methods: { logout() {…