vue实现简单的前端分页功能

思路:假设每页显示10条,一共100条,那么共10页,第一页显示1-10条数据,第二页显示11-20条数据…以此类推是不是有思路了

代码:

 
 
 
let productList = [];
for (let i = 0; i < 99; i++) {
    productList.push({
        name: "第" + i + "瓶奶酪",
        count: Math.random() * 100
    });
}
export default {
    data() {
        return {
            productList, //所有数据
            totalPage: 1, // 统共页数,默认为1
            currentPage: 1, //当前页数 ,默认为1
            pageSize: 10, // 每页显示数量
            currentPageData: [] //当前页显示内容
        };
    },
    mounted() {
        // 计算一共有几页
        this.totalPage = Math.ceil(this.productList.length / this.pageSize);
        // 计算得0时设置为1
        this.totalPage = this.totalPage == 0 ? 1 : this.totalPage;
        this.setCurrentPageData();
    },
    methods: {
        // 设置当前页面数据,对数组操作的截取规则为[0~10],[10~20]...,
       setCurrentPageData() {
            let begin = (this.currentPage - 1) * this.pageSize;
            let end = this.currentPage * this.pageSize;
            this.currentPageData = this.productList.slice(
                begin,
                end
            );
        },
        //上一页
        prevPage() {
            console.log(this.currentPage);
            if (this.currentPage == 1) return;
         
             this.currentPage--;
             this.setCurrentPageData();
            
        },
        // 下一页
        nextPage() {
            if (this.currentPage == this.totalPage)return ;
 
             this.currentPage++;
             this.setCurrentPageData();
            
        }
    }
};

html代码:

    <div class="wrap">
        <main>
            <table>
                <thead>
                    <tr>
                        <th>名称</th>
                        <th>数量</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item,index) in currentPageData" :key="index">
                        <td>
                            {{item.name}}
                        </td>
                        <td>
                            {{item.count}}
                        </td>
                    </tr>
                </tbody>
            </table>
        </main>
        <footer>
            <button @click="prevPage()">
                上一页
            </button>
            <span>{{currentPage}}/{{totalPage}}</span>
            <button @click="nextPage()">
                下一页
            </button>
        </footer>
    </div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值