Vue组件实现分页

一.介绍

    本方法利用vue的父子组件实现分页功能,UI来自bootstrap。实现效果是最大页数小于五时全部显示,分页只显示五个页数,具体页码显示范围根据当前页与最大页数来变换。效果如下图所示:

Vue组件实现分页_第1张图片

               

二.子组件部分

    

	Vue.component('page-divide',{
		props:['index','maxpage','curpage'],
		computed:{
			pagelist:function(){	//控制页面显示页码范围的方法
					if(this.maxpage<5){
						return  this.index;
						}else{
							if(this.curpage-2<=0){
								return this.index;
							}else if(this.curpage+2>this.maxpage){
								 return this.maxpage+this.index-5;
							}else{
								return this.curpage+this.index-3;
							}
						}
			}
		},
		template:'
  • {{pagelist}}
  • ', methods:{ switchpage:function(){ this.$emit('switchpage',this.pagelist); } } });
        我们定义了一个标签名为page-divide的子组件由父组件传入三个属性,index:当前循环的下标,maxpage:最大页数,curpage:当前页面页码。子组件的属性pagelist,由根据computed计算得到,当前页等于pagelist时,模板的li标签样式变为active。点击模板中a标签,调用子组件switchpage方法,该方法触发父组件switchpage方法。

    二.父组件部分

        首先创建父组件的vm实例,

         父组件使用Dom元素作为模板:

        vue实例:

    var vmstand = new Vue({
    		el:'#stand',
    		data:{
    			currentpage:currentpage,
    			maxpage:0
    		},computed:{
    			pagesize:function(){
    				return this.maxpage>5?5:this.maxpage;
    			}
    			},
    		methods:{
    			getData:function(page){
    				this.currentpage=page;
    				var _self=this;
    				_self.flag=false;
    				$.ajax({type:"POST",url:"staticInfoController/getPage.do",
    					data : {'pageSize':1,'currentPage':page,'params':this.condition,'type':'basic.Standard'},async:false,
    					dataType:"text",success:function(data) {
    					data = eval("("+data+")");
    					if(page<=data.maxPage&&page>0){
    						_self.info =data.list;
    						_self.maxpage=data.maxPage;
    						_self.currentpage=page;
    						_self.flag=true;
    					}else if(page<=0){
    						_self.getData(1);
    					}else{
    						_self.getData(page-1);
    					}
    					_self.$nextTick(function(){
    						_self.initClickChecked();//业务需要方法,在dom加载结束后调用
    					})
    					}});
    			}}})

         其中page-divide 就是定义的子组件。因为没有引用vue-resource,所以直接通过ajax得到数据,注意vue的this在ajax里面不能直接用,因为ajax里的this指的是调用本次ajax请求时传递的options参数。 el中使用v-for进行循环,循环次数为pagesize。在父组件中设置index,maxpage,curpage三个属性传入子组件。当子组件触发父组件switchpage方法时,父组件调用getData方法,重新获得数据。

    你可能感兴趣的:(Vue)