Vue分页器组件

275 阅读1分钟

需要自定义分页器样式时,自己手写分页器组件

<template>
  <div class="pagination">
    <!-- 前段:上一页和第一页 -->
    <button :disabled="pageNo == 1" @click="pageNo - 1">上一页</button>
    <button v-if="startAndEnd.start > 1" :class="{ active: pageNo == 1 }" @click="jump(1)">1</button>
    <button v-if="startAndEnd.start > 2">···</button>
    <!-- 中间连续部分 -->
    <button v-for="(page, index) in middleNum" :key="index" :class="{ active: pageNo == page }" @click="jump(page)">{{ page }}</button>
    <!-- 后段:下一页和最后一页 -->
    <button v-if="startAndEnd.end < totalPage - 1">···</button>
    <button v-if="startAndEnd.end < totalPage" :class="{ active: pageNo == totalPage }" @click="jump(totalPage)">{{ totalPage }}</button>
    <button :disabled="pageNo == totalPage" @click="pageNo + 1">下一页</button>
    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  data() {
    return {
      // pageNo当前页数
      pageNo: 1,
      // pageSize每页几个内容
      pageSize: 3,
      // total一共有多少条内容
      total: 90,
      // continues中间连续部分
      continues: 5
    }
  },
  computed: {
    // 有多少页
    totalPage() {
      return Math.ceil(this.total / this.pageSize)
    },
    // 连续部分开始和结束
    startAndEnd() {
      const { continues, pageNo, totalPage } = this
      let start = 0,
        end = 0
      // 当需要的页数大于总页数时(当页数小于5时)
      if (continues > totalPage) {
        start = 1
        end = totalPage
      } else {
        // 当页数正常时
        start = pageNo - parseInt(continues / 2)
        end = pageNo + parseInt(continues / 2)
        if (start < 1) {
          start = 1
          end = continues
        }
        if (end > totalPage) {
          end = totalPage
          start = totalPage - continues + 1
        }
      }
      return { start, end }
    },
    // 中间连续部分
    middleNum() {
      const { startAndEnd } = this
      let arr = []
      for (let i = startAndEnd.start; i <= startAndEnd.end; i++) {
        arr.push(i)
      }
      return arr
    }
  },
  methods: {
    // 点击跳转该页
    jump(page) {
      this.pageNo = page
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>