需求
前台页面,只显示上一页下一页,总页数和当前页在另外一个地方显示,所以只需要封装上一页下一页的功能。
上一页下一页为图片,悬浮后显示悬浮后的图片。
代码
utils - local-img.js
const allIcon = {
// 分页
page_prev: require('@/assets/images/page_prev.png'),
page_next: require('@/assets/images/page_next.png'),
page_prev_hover: require('@/assets/images/page_prev_hover.png'),
page_next_hover: require('@/assets/images/page_next_hover.png'),
}
export default allIcon
components - pagination.js
<template>
<div class="pagination clearfix">
<div class="previous fl">
<img class="page_prev" :src="allIcon.page_prev" alt="" @click="handlePrev">
<img class="page_prev_hover" :src="allIcon.page_prev_hover" alt="" @click="handlePrev">
</div>
<div class="next fr">
<img class="page_next" :src="allIcon.page_next" alt="" @click="handleNext">
<img class="page_next_hover" :src="allIcon.page_next_hover" alt="" @click="handleNext">
</div>
</div>
</template>
<script>
import allIcon from '@/utils/local-img'
export default {
props: ['totalCounts', 'currentPage'],
data() {
return {
allIcon: allIcon,
pageNum: this.currentPage,
totalPages: 1,
}
},
created () {
this.getPages()
},
methods: {
getPages () {
// 计算总页数
this.totalPages = Math.ceil(this.totalCounts / 4);
},
handlePrev () {
if (this.pageNum <= 1) {
return
}
this.pageNum--
this.$emit('on-change', this.pageNum)
},
handleNext () {
if (this.pageNum >= this.totalPages) {
return
}
this.pageNum++
this.$emit('on-change', this.pageNum)
},
},
watch: {
currentPage (n) {
this.pageNum = n
},
totalCounts (n) {
if (n) {
this.getPages()
}
}
}
}
</script>
<style lang="less" scoped>
.pagination {
width: 1.44rem;
.previous {
.page_prev, .page_prev_hover{
width: 0.72rem;
height: 0.72rem;
cursor: pointer;
}
.page_prev {
display: block;
}
.page_prev_hover {
display: none;
}
&:hover {
.page_prev {
display: none;
}
.page_prev_hover {
display: block;
}
}
}
.next {
.page_next, .page_next_hover{
width: 0.72rem;
height: 0.72rem;
cursor: pointer;
}
.page_next {
display: block;
}
.page_next_hover {
display: none;
}
&:hover {
.page_next {
display: none;
}
.page_next_hover {
display: block;
}
}
}
}
</style>
使用
全局注册后使用
<pagination :totalCounts='totalCounts' :currentPage='currentPage' @on-change="handlePage"></pagination>
data
totalCounts: 0,
currentPage: 1,
totalPages: 1,
methods
// 分页
handlePage (num) {
this.currentPage = num
this.getInfoList()
},
// 列表
getInfoList () {
const params = {
pageNum: this.currentPage,
pageSize: 4,
}
api.info.infoList(params).then(res => { // 请求接口
if (res.status == 200) {
this.infoList = res.data.list
this.totalCounts = res.data.total
this.totalPages = res.data.pages
}
})
},