用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>

 

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