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

代碼:
1.注冊一個組件
js
Vue.component('pagination',{
template:'#paginationTpl',
replace:true,
props:['cur','all','pageNum'],
methods:{
//頁碼點擊事件
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 = [];
//計算左右頁碼
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>頁</a></li>
</ul>
</nav>
</script>
HTML:
<div id='item_list'> ... <pagination :cur="1" :all="pageAll" :page-num="10" @page-to="loadList"></pagination> </div>
當點擊分頁鏈接的時候,通過watch cur,子組件分發 page-to 事件,通過 @page-to="loadList" 標簽指定使用父組件 loadList 方法處理事件,父組件接收到page值然後ajax加載數據,根據服務端返回計算並更新自身的 pageAll 值,因為子組件prop通過 :all="pageAll" 動態綁定了父組件的pageAll對象,所以子組件會聯動更新。
附上一個簡單的表格組件例子:
var vm = new Vue({
el: "#item_list",
data: {
items : [],
//分頁參數
pageAll:0, //總頁數,根據服務端返回total值計算
perPage:10 //每頁數量
},
methods: {
loadList:function(page){
var that = this;
$.ajax({
url : "/getList",
type:"post",
data:{"page":page,"perPage":this.perPage},
dataType:"json",
error:function(){alert('請求列表失敗')},
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);//計算總頁數
}
}
});
},
//初始化
init:function(){
this.loadList(1);
}
}
});
vm.init();
精彩專題分享:jquery分頁功能操作 JavaScript分頁功能操作
本文已被整理到了《Vue.js前端組件學習教程》,歡迎大家學習閱讀。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。