当前位置:首页 > VUE

vue实现搜索分页

2026-03-29 21:57:55VUE

实现搜索分页的步骤

创建Vue组件

在Vue项目中创建一个组件,包含搜索框和分页控件。确保组件有data属性存储搜索关键词和分页信息。

<template>
  <div>
    <input v-model="searchQuery" placeholder="Search..." @input="handleSearch" />
    <table>
      <tr v-for="item in paginatedData" :key="item.id">
        <td>{{ item.name }}</td>
      </tr>
    </table>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">Previous</button>
      <span>Page {{ currentPage }} of {{ totalPages }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
    </div>
  </div>
</template>

设置初始数据

在组件的data中定义初始状态,包括搜索关键词、当前页数和每页显示数量。

data() {
  return {
    searchQuery: '',
    allData: [], // 从API获取的原始数据
    filteredData: [], // 过滤后的数据
    currentPage: 1,
    itemsPerPage: 10
  }
}

实现搜索功能

添加一个方法来处理搜索逻辑,过滤数据并重置当前页数。

methods: {
  handleSearch() {
    this.filteredData = this.allData.filter(item => 
      item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
    );
    this.currentPage = 1;
  }
}

计算分页数据

使用计算属性来获取当前页的数据和总页数。

computed: {
  totalPages() {
    return Math.ceil(this.filteredData.length / this.itemsPerPage);
  },
  paginatedData() {
    const start = (this.currentPage - 1) * this.itemsPerPage;
    const end = start + this.itemsPerPage;
    return this.filteredData.slice(start, end);
  }
}

添加分页导航

实现翻页方法,确保页数在有效范围内。

methods: {
  nextPage() {
    if (this.currentPage < this.totalPages) {
      this.currentPage++;
    }
  },
  prevPage() {
    if (this.currentPage > 1) {
      this.currentPage--;
    }
  }
}

获取初始数据

mounted钩子中获取初始数据,并初始化过滤后的数据。

mounted() {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => {
      this.allData = data;
      this.filteredData = data;
    });
}

样式调整

为分页控件添加基本样式,确保用户界面友好。

vue实现搜索分页

.pagination {
  margin-top: 20px;
}
.pagination button {
  margin: 0 5px;
}

注意事项

  • 确保搜索功能对大小写不敏感,提升用户体验。
  • 分页控件应禁用不可用的按钮,避免无效操作。
  • 考虑添加加载状态,在数据获取时显示提示信息。

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

相关文章

vue实现页面截屏

vue实现页面截屏

使用html2canvas库实现截屏 html2canvas是一个流行的JavaScript库,可以将DOM元素转换为Canvas图像。在Vue项目中安装html2canvas: npm insta…

实现简易vue

实现简易vue

实现简易 Vue 的核心思路 Vue 的核心功能包括数据响应式、模板编译和虚拟 DOM。以下是一个简易实现方案,涵盖核心功能模块。 数据响应式系统 通过 Object.defineProperty…

vue 实现打印

vue 实现打印

Vue 实现打印功能的方法 在Vue项目中实现打印功能,可以通过以下几种方式实现: 使用window.print()方法 通过调用浏览器的原生打印API实现基础打印功能,适用于简单内容打印。 //…

vue 实现评分

vue 实现评分

Vue 实现评分功能 在 Vue 中实现评分功能可以通过多种方式完成,包括使用第三方组件库或自定义实现。以下是两种常见的方法: 使用第三方组件库(如 Element UI) Element UI 提…

vue实现通讯

vue实现通讯

Vue 组件通讯方法 父子组件通讯 父组件向子组件传递数据通过 props,子组件向父组件传递数据通过 $emit 事件。 父组件模板: <child-component :message=…

vue最佳实现

vue最佳实现

Vue 最佳实践 组件设计 组件应遵循单一职责原则,每个组件只负责一个功能模块。命名采用 PascalCase(如 UserProfile.vue),模板中使用 kebab-case(如 <us…