分頁(yè)一般和表格一起用,分頁(yè)鏈接作為表格的一部分,將分頁(yè)鏈接封裝成一個(gè)獨(dú)立的組件,然后作為子組件嵌入到表格組件中,這樣比較合理。
效果:

代碼:
1.注冊(cè)一個(gè)組件
js
Vue.component('pagination',{ template:'#paginationTpl', replace:true, props:['cur','all','pageNum'], methods:{ //頁(yè)碼點(diǎn)擊事件 btnClick: function(index){ if(index != this.cur){ this.cur = index; } } }, watch:{ "cur" : function(val,oldVal) { this.$dispatch('page-to', val); } }, computed:{ indexes : function(){ var list = []; //計(jì)算左右頁(yè)碼 var mid = parseInt(this.pageNum / 2);//中間值 var left = Math.max(this.cur - mid,1); var right = Math.max(this.cur + this.pageNum - mid -1,this.pageNum); if (right > this.all ) { right = this.all} while (left <= right){ list.push(left); left ++; } return list; }, showLast: function(){ return this.cur != this.all; }, showFirst: function(){ return this.cur != 1; } } });模板:
<script type="text/template" id="paginationTpl"> <nav v-if="all > 1"> <ul class="pagination"> <li v-if="showFirst"><a href="javascript:" @click="cur--">«</a></li> <li v-for="index in indexes" :class="{ 'active': cur == index}"> <a @click="btnClick(index)" href="javascript:">{{ index }}</a> </li> <li v-if="showLast"><a @click="cur++" href="javascript:">»</a></li> <li><a>共<i>{{all}}</i>頁(yè)</a></li> </ul> </nav></script>HTML:
<div id='item_list'> ... <pagination :cur="1" :all="pageAll" :page-num="10" @page-to="loadList"></pagination></div>
當(dāng)點(diǎn)擊分頁(yè)鏈接的時(shí)候,通過watch cur,子組件分發(fā) page-to 事件,通過 @page-to="loadList" 標(biāo)簽指定使用父組件 loadList 方法處理事件,父組件接收到page值然后ajax加載數(shù)據(jù),根據(jù)服務(wù)端返回計(jì)算并更新自身的 pageAll 值,因?yàn)樽咏M件prop通過 :all="pageAll" 動(dòng)態(tài)綁定了父組件的pageAll對(duì)象,所以子組件會(huì)聯(lián)動(dòng)更新。
附上一個(gè)簡(jiǎn)單的表格組件例子:
var vm = new Vue({ el: "#item_list", data: { items : [], //分頁(yè)參數(shù) pageAll:0, //總頁(yè)數(shù),根據(jù)服務(wù)端返回total值計(jì)算 perPage:10 //每頁(yè)數(shù)量 }, methods: { loadList:function(page){ var that = this; $.ajax({ url : "/getList", type:"post", data:{"page":page,"perPage":this.perPage}, dataType:"json", error:function(){alert('請(qǐng)求列表失敗')}, success:function(res){ if (res.status == 1) { that.items = res.data.list; that.perPage = res.data.perPage; that.pageAll = Math.round(res.data.total / that.perPage);//計(jì)算總頁(yè)數(shù) } } }); }, //初始化 init:function(){ this.loadList(1); } } }); vm.init();精彩專題分享:jquery分頁(yè)功能操作 JavaScript分頁(yè)功能操作
本文已被整理到了《Vue.js前端組件學(xué)習(xí)教程》,歡迎大家學(xué)習(xí)閱讀。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注