天天看點

用vuejs寫一個分頁元件

今天記錄用vuejs2來寫一個分頁元件

有些注解定義我說的并不是很準确,主要是友善自己了解寫的,請大家包涵 ...

代碼的github網址 : https://github.com/fengliting/vue-page,裡面給了詳細的注解和補充一些方法

頁面的html

<!-- 分頁 --> <m-page @on-bottompage="bottompage"></m-page> 解釋:@on-bottompage="bottompage":點選送出分頁的方法,這個也是綁定到vm執行個體裡面的方法,相當于子元件傳資訊給到父元件,如果解釋看不是很懂,等會看代碼

//定義元件

Vue.component("m-page",{

//定義初始化的一些資料

data:function(){

return {

inputppage:'',

pagenums:10,

cur:1,

}

},

//拿到父元件傳過來的值

props:['bottompage'],

//模闆html,會顯示到html

template:`

<div class="Activepage"> <div class="row"> <div class="col-sm-6"> <ul class="pagination" v-cloak> <li :class="{'disabled':cur == 1}"><a @click="cur--,pageclick()" >&lsaquo;</a></li> <li :class="{'active':cur == index}" v-for="index in indexs"><a @click="btnclick(index,$event)">{{index}}</a></li> <li :class="{'disabled':cur == pagenums}"><a @click="cur++,pageclick()" >&rsaquo;</a></li> </ul> </div> <div class="col-sm-6 page-confirm"> 共 {{pagenums}} 頁 到第 <input type="text" name="page_id" class="no-width-form-control text-center" v-model="inputpage" size="1"> 頁\ <button type="button" class="btn btn-primary" @click="pagesubmit($event)">确定</button> </div> </div> </div>

`,

  //事件處理器,定義方法都寫這裡

methods:{

pagesubmit:function(){

this.$emit("on-bottompage", this.inputpage); this.cur = this.inputpage

},

btnclick:function(){

this.$emit("on-bottompage",index);

     if(index!=this.cur){

this.cur = index}

},

pageclick:function(){

     this.$emit("on-bottompage",this.cur)

}

},

//計算屬性

computed:{

indexs:function(){

var left = 1; var right = this.pagenums; var arr = []; // 展示底部的分頁一直有5個 if (this.pagenums >= 5) { if (this.cur > 3 && this.cur < this.pagenums - 2) { //這裡有個坑,一定要記得轉化為parseInt left = parseInt(this.cur) - 2 right = parseInt(this.cur) + 2 } else { if (this.cur <= 3) { left = 1 right = 5 } else { right = this.pagenums left = this.pagenums - 4 } } } while (left <= right) { arr.push(left) left++ } // console.log(arr) return arr

}

},

})

//執行個體接收子元件的方法

new Vue({ el:'#page', data:{

}, methods:{ bottompage:function(inputpage){ console.log('向父集傳送目前頁碼'+inputpage) } } })

代碼的github網址 : https://github.com/fengliting/vue-page,裡面給了詳細的注解和補充一些方法,如果喜歡給顆星星吧