Paging is generally used together with tables. The paging link is used as part of the table. It is more reasonable to encapsulate the paging link into an independent component and then embed it into the table component as a sub-component.
Effect:
Code:
1. Register a component
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; } } });
Template:
<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>
When a paging link is clicked, the child component distributes the page-to event through watch cur, and the parent is specified through the @page-to="loadList" tag. The component loadList method handles the event. The parent component receives the page value and then loads the data with ajax. It calculates and updates its own pageAll value based on the server return, because the child component prop dynamically binds the parent component's pageAll object through: all="pageAll". Therefore, the subcomponents will be updated together.
Attached is a simple table component example:
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.ceil(res.data.total / that.perPage);//计算总页数 } } }); }, //初始化 init:function(){ this.loadList(1); } } }); vm.init();
Thanks for reading, I hope it can help everyone, thank you for your support of this site!
For more Javascript vue.js table paging, ajax asynchronous data loading related articles, please pay attention to the PHP Chinese website!