###### tags:Vue # VUE-前端處理分頁功能 首先在**data**裡建立變數 ```javascript= datas: [],//要呈現的資料 perpage: 10, //一頁的資料數 currentPage: 1 ``` 在**computed**裡新增方法 ```javascript= computed: { totalPage() { return Math.ceil(this.datas.length / this.perpage) //Math.ceil()取最小整數 }, pageStart() { return (this.currentPage - 1) * this.perpage //取得該頁第一個值的index } pageEnd() { return this.currentPage * this.perpage //取得該頁最後一個值的index } } ``` 在**methods**裡新增方法 ```javascript= methods: { setPage(page) { if(page <= 0 || page > this.totalPage) { return } this.currentPage = page } } ``` 最後在html裡綁定事件 ```htmlembedded= <ul> <li v-for="item in datas.slice(pageStart, pageEnd)"> {{ item }} </li> </ul> //pagination <ul class="pagination"> <li class="page-item" @click.prevent="setPage(currentPage-1)"> <a class="page-link" href="#" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> <li class="page-item" :class="{'active': (currentPage === (n))}" v-for="(n, index) in totalPage" :key="index" @click.prevent="setPage(n)"> <a class="page-link" href="#">{{ n }}</a> </li> <li class="page-item" @click.prevent="setPage(currentPage+1)"> <a class="page-link" href="#" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> </ul> ``` ## slice(begin, end) **begin** -從這個索引開始 if slice(-2)表示陣列由最末項開始取 **end** -到這個索引**前**停止 *ex: slice(1,4)取index1,2,3*