1 .起因
今日看完element中分頁器的源碼實現,比較簡單,遂自己按著理解實現了一個簡單的分頁器,記錄下來,以便日后溫習.
2.實現難點
分頁器的實現難點主要是什么時候顯示分頁器的省略, 我的思路是: 規定一個值foldPage, 意為當前最多顯示的標簽數,當總頁數超過即顯示省略.省略分為左邊省略(folder1)和右邊省略(folder2),布局代碼如下:
<div class="pagination" @click="pageClick">    <button class="pre">上一頁</button>    <ul class="pages">      <li :class="['first', { 'active' : current == 1 }]" v-if="total">        1      </li>      <li :class="[ testLeft,goback]"        v-show="showPreMore"        @mouseenter="testLeft='more-left'"        @mouseleave="testLeft='more'"></li>      <li :class="['page-item', { 'active' : current == item }]" v-for="item in $pages">        {{ item }}      </li>      <li :class="[ testRight,gogo]"         v-show="showNextMore"        @mouseenter="testRight='more-right'"        @mouseleave="testRight='more'"></li>      <li :class="['last', { 'active' : current == $last }]" v-if="total">        {{ $last }}      </li>    </ul>    <button class="next">下一頁</button>  </div>$pages是一個計算屬性,用于動態生成中間的頁碼,以及控制folder1和folder2的顯示,代碼如下:
computed:{    // 中間頁數組    $pages(){      const foldPage = this.foldPage       const current = Number(this.current)      const halfFoldPage = Math.floor((foldPage-2)/2)       if (this.$last > foldPage){        if (current - halfFoldPage > 2){          this.showPreMore = true        }else {          this.showPreMore = false        }        if (current + halfFoldPage < this.$last){          this.showNextMore = true        }else {          this.showNextMore = false        }      }      let array = []      // folder1顯示      if (this.showNextMore && !this.showPreMore){        for(let i = 2; i < foldPage; i++){          array.push(i)        }      // folder1 和 folder2都顯示      }else if ( this.showPreMore && this.showNextMore ){        for(let i = current - halfFoldPage; i <= current + halfFoldPage; i++ ){          array.push(i)        }      // folder2顯示      }else if (!this.showNextMore && this.showPreMore){        // 當folder2顯示的時候,頁碼不能大于$last,需要往前多顯示差額        let dis = current + halfFoldPage - this.$last + 1;        for(let i = current - halfFoldPage - dis ; i < this.$last; i++){          array.push(i)        }      // 都不顯示      }else {        for(let i = 2; i < this.$last; i++){          array.push(i)        }      }      return array    },    // 總頁數    $last(){                   return Math.ceil(this.total/this.size)    }  }所有的點擊都用一個函數處理, 根據e.target判斷點擊的目標.從而做出相應的邏輯:
新聞熱點
疑難解答
圖片精選