当前位置:首页 > VUE

vue实现分页请求

2026-03-09 14:50:02VUE

实现分页请求的基本思路

在Vue中实现分页请求通常需要结合后端API的分页参数(如pagepageSize)以及前端的分页组件(如el-pagination)。核心逻辑是通过改变分页参数触发数据重新请求。

分页组件与数据绑定

使用el-pagination组件绑定分页参数,监听页码变化事件:

<el-pagination
  @current-change="handlePageChange"
  :current-page="currentPage"
  :page-size="pageSize"
  :total="total">
</el-pagination>

定义分页数据与请求方法

在Vue的data中定义分页相关变量,并在methods中实现请求逻辑:

data() {
  return {
    currentPage: 1,
    pageSize: 10,
    total: 0,
    listData: []
  }
},
methods: {
  async fetchData() {
    const res = await axios.get('/api/list', {
      params: {
        page: this.currentPage,
        pageSize: this.pageSize
      }
    });
    this.listData = res.data.items;
    this.total = res.data.total;
  },
  handlePageChange(page) {
    this.currentPage = page;
    this.fetchData();
  }
}

初始化加载数据

mounted钩子中触发首次数据加载:

mounted() {
  this.fetchData();
}

完整组件示例

结合模板与逻辑的完整组件示例:

vue实现分页请求

<template>
  <div>
    <ul>
      <li v-for="item in listData" :key="item.id">{{ item.name }}</li>
    </ul>
    <el-pagination
      @current-change="handlePageChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next">
    </el-pagination>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      listData: []
    }
  },
  methods: {
    async fetchData() {
      const res = await axios.get('/api/list', {
        params: {
          page: this.currentPage,
          pageSize: this.pageSize
        }
      });
      this.listData = res.data.items;
      this.total = res.data.total;
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchData();
    }
  },
  mounted() {
    this.fetchData();
  }
}
</script>

注意事项

确保后端API支持分页参数,通常需要返回total字段用于前端计算总页数。对于复杂场景,可以增加每页条数切换功能,通过监听page-size-change事件动态调整pageSize

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

相关文章

vue alert实现

vue alert实现

使用 Vue 实现 Alert 组件 在 Vue 中实现 Alert 组件可以通过自定义组件或结合第三方库完成。以下是几种常见方法: 自定义 Alert 组件 创建一个可复用的 Alert 组件,通…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…

vue实现接口

vue实现接口

在 Vue 中实现接口请求 Vue 本身不直接提供 HTTP 请求功能,通常需要借助第三方库如 axios 或 fetch 来实现接口请求。以下是几种常见方法: 使用 axios 发送请求 安装 a…

vue 实现工具

vue 实现工具

Vue 实现工具的方法 使用 Vue 实现工具功能可以通过多种方式完成,具体取决于工具的类型和需求。以下是几种常见的方法: 组件化实现 创建一个独立的 Vue 组件来封装工具功能。例如,实现一个计…

vue实现123456

vue实现123456

Vue 实现数字 123456 的显示 在 Vue 中显示数字 123456 非常简单,可以通过以下方法实现: 方法一:直接在模板中显示 <template> <div>…

vue导航实现

vue导航实现

Vue 导航实现方法 在 Vue 中实现导航功能通常涉及路由配置、组件设计和状态管理。以下是几种常见的实现方式: 使用 Vue Router 实现基础导航 安装 Vue Router: npm i…