分頁,是在業務中經常要用到,為了節省用戶流量和提升用戶體驗
講一下思路:
首先是定義頁號currentPage 和 頁大小pagesize,用一個數組保存總數據;
用一個計算屬性page_arrs,作用是 讓頁面展示的是我們所需要的頁面
而我們在page_arrs中要分割原數組,用一個slice()方法進行分割;
在控件button上綁定點擊方法,對頁號currentPage進行修改,從而修改整個頁面展示
具體看以下代碼
代碼:
data () { return { arrs : [ {name:'Otto',id:1}, {name:'Jacob',id:2}, {name:'Larry',id:3}, {name:'Tim',id:4}, {name:'Tom',id:5}, {name:'Jack',id:6}, {name:'Otto',id:1}, {name:'Jacob',id:2}, {name:'Larry',id:3}, {name:'Tim',id:4}, {name:'Tom',id:5}, {name:'Jack',id:6}, {name:'Otto',id:1}, {name:'Jacob',id:2}, {name:'Larry',id:3}, {name:'Tim',id:4}, {name:'Tom',id:5}, {name:'Jack',id:6} ], currentPage : 1,//當前頁號 pagesize :10 //每頁大小 } }
<table class="table table-hover "> <thead> <tr> <th class="number">序號</th> <th >題目</th> <th class="del">刪除</th> </tr> </thead> <tbody> <tr class="tr" v-for="(item,index) in page_arrs" :key="index"> <th>{{index+1}}</th> <td>{{item.name}}</td> <td><a href="">刪除</a></td> </tr> </tbody> </table> <div class="page"> <button class="btn btn-default" type="submit" @click="primaryPage">首頁</button> <button class="btn btn-default" type="submit" @click="prePage">上頁</button> <button class="btn btn-default" type="submit">{{current_page}}/{{Math.ceil(arrs.length/pagesize)}}</button> <button class="btn btn-default" type="submit" @click="nextPage">下頁</button> <button class="btn btn-default" type="submit" @click="lastPage">尾頁</button> </div>
computed:{ page_arrs(){ let {currentPage,pagesize} = this return this.arrs.slice((currentPage-1)*pagesize,currentPage*pagesize) }, current_page(){ return this.currentPage }
},
methods: { primaryPage(){ this.currentPage = 1 }, prePage(){ if(this.currentPage == 1){ return } this.currentPage = this.currentPage - 1 }, nextPage(){ if(this.currentPage == Math.ceil(this.arrs.length/this.pagesize)){ return } this.currentPage = this.currentPage + 1 }, lastPage(){ this.currentPage = Math.ceil(this.arrs.length/this.pagesize) } },