vue3.x 前端分页

258 阅读1分钟

在Vue 3中实现分页功能,通常涉及到以下几个步骤:

  1. 数据和状态初始化:在 data 部分,定义了相关的数据状态,其中包括 tableData(当前页显示的数据),allTableData(存储所有从后端获取的数据),pagination 对象(存储分页相关信息,如当前页码 currentPage,每页显示的数据条数 pageSize,以及总数据条数 total)等。
  2. 获取流水线历史数据:在组件的 created 钩子函数中,调用 getTableData 方法,该方法通过 getPipelineInfoHistory API 获取流水线的所有历史记录,并存储在 allTableData 中。同时,更新 pagination.total 为获取的数据总条数,以正确显示分页信息。
  3. 分页处理sliceData 方法是实现分页核心的地方。它根据当前页码 currentPage 和每页显示的数据条数 pageSize,从 allTableData 中计算出当前页应该显示的数据片段,并将其赋值给 tableData。这样,表格就只显示当前页的数据。
  4. 页码变化处理handleCurrentChange 方法作为 el-pagination 组件的 @current-change 事件的处理函数,当用户切换页码时被触发。该方法更新当前页码 currentPage,然后调用 sliceData 方法刷新表格数据。
<template>
  <div class="container">
    ...
    <el-table :data="tableData" :pagination="pagination">
      ...
    </el-table>
    <div class="page-foot" style="display: flex; justify-content:right; margin: 10px">
      <el-config-provider :locale="lang">
        <div class="custom-page" style="color: #606266">
          每页 100 条
        </div>
        <el-pagination background :current-page="pagination.currentPage" :page-size="pagination.pageSize" :total="pagination.total" layout="total, prev, pager, next" @current-change="handleCurrentChange"/>
      </el-config-provider>
    </div>
  </div>
</template>

<script>
import { getPipelineInfoHistory, apiAddAccessStatistics } from "@/api/jenkinsPipeline";
import zhCn from "element-plus/lib/locale/lang/zh-cn";

export default {
  name: 'jenkins_pipeline',
  data () {
    return {
      tableData: [],
      allTableData: [], // 存储所有数据
      lang: zhCn,
      pagination: {
        currentPage: 1, // 当前页码
        pageSize: 100, // 每页显示的数据条数
        total: 0, // 总数据条数
      },
    }
  },
  created() {
    this.getTableData()
  },

  methods: {
    getTableData() {
      getPipelineInfoHistory({ job_name: this.job_name }).then(response=>{
        if (response.data) {
          this.allTableData = response.data
          this.pagination.total = response.data.length
          this.sliceData()
        }
      })
    },

    handleCurrentChange(newPage) {
      this.pagination.currentPage = newPage
      // 在这里调用后端API获取新的分页数据
      this.sliceData()
    },
    
    sliceData() {
      const start = (this.pagination.currentPage - 1) * this.pagination.pageSize
      const end = start + this.pagination.pageSize
      this.tableData = this.allTableData.slice(start, end)
    }
},
}

</script>
<style scoped>
.container {
  margin: 20px;
}
</style>