参考前辈的demo,所以先放上原demo的git地址:👻
https://github.com/cycgit/vue-pagination
按照惯例,先引入必须的资源,然后在项目的html中加入分页模板:
<div id="app" >
<vue-nav :cur="cur" :all="all" :url="url" :callback="callback"></vue-nav>
</div>
js代码照样搬就可以了:
var app = new Vue({
el: '#app',
data:{
cur: 1,
all: 23,
url:'localhost:6677/queryList'
},
components:{
'vue-nav': Vnav
},
methods:{
callback(data) {
//TODO
}
}
})
这里 cur是当前页,all是总页数,url是查询列表服务的url地址,然后看一下组件的处理
(function () {
var tm = '<div class="page-bar">' +
'<ul>' +
'<li v-if="cur!=1" style="margin-left: 10px"><a @click="btnClick(cur-1)">上一页</a></li>' +
'<li v-for="index in indexs" v-bind:class="{ active: cur == index}" style="margin-left: 10px">' +
'<a v-on:click="btnClick(index)" >{{ index }}</a>' +
'</li>' +
'<li v-if="cur!=all" style="margin-left: 10px"><a @click="btnClick(cur+1)">下一页</a></li>' +
'<li style="margin-left: 10px"><a>共<i>{{all}}</i>页</a></li>' +
'</ul>' +
'</div>'
var navBar = Vue.extend({
template: tm,
props: {
cur: {
type: [String, Number],
required: true
},
all: {
type: [String, Number],
required: true
},
url: {
type: [String, Number],
required: true
},
callback: {
default() {
return function callback() {
// todo
}
}
}
},
computed: {
indexs() {
var left = 1
var right = this.all
var ar = []
if (this.all >= 11) {
if (this.cur > 5 && this.cur < this.all - 4) {
left = this.cur - 5
right = this.cur + 4
} else {
if (this.cur <= 5) {
left = 1
right = 10
} else {
right = this.all
left = this.all - 9
}
}
}
while (left <= right) {
ar.push(left)
left++
}
return ar
}
},
methods: {
btnClick(page) {
if (page != this.cur) {
this.callback(page)
}
//这里可以发送ajax请求
}
}
})
window.Vnav = navBar
})()
整个插件整合之后的效果如下:
谢谢观赏! 😂