我是自己简单封装了一个Pagination 组件
<script type="text/x-template" id="fy-pagination-template">
<nav class="pagination-nav pull-right">
<ul class="pagination">
<li>
<a :href="previous" @click.stop.prevent="goPage(previous)" aria-label="上一页">«</a>
</li>
<template v-for="(key, value) in pages">
<li><a :href="value" @click.stop.prevent="goPage(value)">@{ key + 1 }</a></li>
</template>
<li>
<a :href="next" @click.stop.prevent="goPage(next)" aria-label="下一页">»</a>
</li>
</ul>
</nav>
</script>
<script>
Vue.component('fy-pagination', {
template: '#fy-pagination-template',
data: function () {
return {
pages: [],
next: '#',
previous: '#'
}
},
methods: {
goPage: function (page) {
if (page && page !== '#')
this.$dispatch('pagination.page.change', page);
}
},
events: {
'pagination.data.ready': function (pagination) {
var current_page = pagination.current_page,
total_pages = pagination.total_pages;
if (current_page < total_pages)
this.next = current_page + 1;
else
this.next = '#';
if (current_page > 1)
this.previous = current_page - 1;
else
this.previous = '#'
var i;
this.pages = [];
for (i = 1; i <= total_pages; i++) {
if (i === current_page)
this.pages.push('#')
else
this.pages.push(i);
}
}
}
});
</script>
然后调用方法如下:
<div id="parentComponet">
<!--- 渲染数据和其他什么的 -->
<fy-pagination></fy-pagination>
</div>
<script>
var vm = new Vue({
methods: {
refresh: function () {
//更新数据
this.$http.get(this.apiUrl).then(
function (res) {
this.items = res.data.data;
// pagination元信息由dingo api的paginator方法提供
this.$broadcast('pagination.data.ready', res.data.meta.pagination);
}, function (res) {
console.log(res.status);
});
},
},
events: {
'pagination.page.change': function (page) {
this.page = page;
this.refresh();
}
}
})
</script>
父子组件之间通过事件进行通信,父组件负责数据的加载,仅将分页信息传给pagination组件。pagination组件内不存api地址,仅保存page number,切换页面时将变更的页码传递给父组件,让父组件刷新数据。
自己造完轮子之后才发现原来有vue-pagination这货,不过也不太喜欢callback的方式(因为需要时刻费心惦记this指向谁....),就一直用自己DIY的分页组件了。希望对你有所帮助 ^_^