用vue自己封装一个分页组件

准备知识:全局配置组件(本文不赘述,可自行百度)

先来看下效果。

非常简单的效果。事件上仅改变页码,无其他。

1、新建文件pagination.vue。简单解释下:先写DOM结构和样式,接着是事件。

  • 写事件很简单,点击按钮改变页码,并传递页码信息给父级。
  • 传递进来的参数需要接收,并赋值给当前组件。
<template>
  <div class="page-wrapper">
    <span>第{{page.currentPage}}页/共{{page.pages}}页</span>
    <span @click="changePage('home')">首页</span>
    <span @click="changePage('pre')">上一页</span>
    <span @click="changePage('next')">下一页</span>
    <span @click="changePage('last')">尾页</span>
  </div>
</template>

<script>
export default {
  props: {
    childMsg: {
      type: Object,
      default: function () {
        return {
          pageSize: 25,
          pages: 0,
          currentPage: 1,
        }
      }
    }
  },
  watch: {/* 总页数初始值问题解决办法:监听值的变化 */
    childMsg: {
      handler(newValue, oldValue) {
        this.page.pages=newValue.pages
      },
      deep: true
    }
  },
  data() {
    return {
      page: {
        pageSize: this.childMsg.pageSize,/* 每页数 */
        pages: this.childMsg.pages,/* 总页数 */
        currentPage: this.childMsg.currentPage,/* 当前页 */
      },
    }
  },
  methods: {
    changePage(type) {/* 仅改变当前页码操作 */
      switch (type) {
        case 'home':
          this.page.currentPage = 1
          break;
        case 'pre':
          if (this.page.currentPage > 1) {
            this.page.currentPage--
          }
          break;
        case 'next':
          if (this.page.currentPage < this.page.pages) {
            this.page.currentPage++
          }
          break;
        case 'last':
          this.page.currentPage = this.page.pages
          break;
        default:
          break;
      }
      this.$emit("callFather", this.page);
    }
  }
};
</script>
<style lang="stylus" scoped>
.page-wrapper
  margin-top: 30px
  font-size: 14px
  text-align: center
  span
    margin: 0 5px
    color: #909399
    &:nth-child(n+2)
      cursor: pointer
</style>

2、最后就是使用。在需要使用的页面引入组件,并传递分页参数信息+回调执行函数,在回调执行函数中按需进行表格数据请求等。(一般分页是用在表格中了)

<template>
  <div class="container">
    <cpagination v-bind:child-msg="page" @callFather='callFather'></cpagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      page: {
        pageSize: 25,
        pages: 10,
        currentPage: 1,
      }
    }
  },
  computed: {

  },
  created() {

  },
  methods: {
    callFather(parm) {
      this.page.currentPage=parm.currentPage    /* 仅改变了页码 */   
      //this.onLoad(this.page) /* 执行请求 */      
    }
  }
};
</script>

<style lang="stylus" scoped></style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章