前端小技巧之 --- 前端实现分页

假设情景:

后端返回总的数据为 tableData,没有分页;

使用element-ui的组件,在前端实现分页

<template>
    <div>
        <el-table :data="resultList" border>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="age" label="年龄"></el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination background layout="total, sizes, prev, pager, next" :total="total" :page-sizes="[2, 4]"
            :page-size="2" :current-page.sync="currentPage" @size-change="handleSizeChange" @current-change="handleCurrentChange">
        </el-pagination>
    </div>
</template>
<script>
export default {
    data() {
        return {
            total: 0,//总的数据条数
            currentPage: 1,//当前页面
            pageSize: 2,//每页有几条
            resultList: [],//当前展示列表
            tableData: [{
                name: "张一",
                age: 20
            }, {
                name: "张二",
                age: 21
            }, {
                name: "张三",
                age: 22
            }, {
                name: "张四",
                age: 23
            }, {
                name: "张五",
                age: 24
            }, {
                name: "张六",
                age: 25
            }]
        }
    },
    created() {
        this.total = this.tableData.length
        this.getData(this.currentPage, this.pageSize)
    },
    methods: {
        //改变每页显示条数
        handleSizeChange(v) {
            this.currentPage = 1
            this.pageSize = v
            this.getData(this.currentPage, this.pageSize)
        },
        //点击跳转到某一页
        handleCurrentChange(v) {
            this.currentPage = v
            this.getData(this.currentPage, this.pageSize)
        },
        // 分页
        getData(page, size) {
            let currentPage = page //当前是第几页
            let pageSize = size //当前每页展示几条
            let list = this.tableData //总的数据
            this.resultList = []

            // 1、如果总的数据小于每页展示条数
            if (list.length < pageSize) {
                this.resultList = list
                return
            }
            // 2、如果是最后一页数据
            if (currentPage * pageSize > list.length) {
                this.resultList = list.slice(parseInt(list.length / pageSize) * pageSize - 1, list.length - 1)
                return
            }

            // 3、如果是整除
            let start = (currentPage - 1) * pageSize
            let end = currentPage * pageSize
            this.resultList = list.slice(start, end)
        }
    }
}
</script>
<style></style>

 

posted @ 2023-02-17 17:33  程序员冒冒  阅读(112)  评论(0编辑  收藏  举报