基於Vue.js的表格分頁組件
有一段時間沒更新文章了,主要是因為自己一直在忙着學習新的東西而忘記分享了,實在慚愧。
這不,大半夜發文更一篇文章,分享一個自己編寫的一個Vue的小組件,名叫BootPage。
不了解Vue.js的童鞋可以移步我的上一篇文章《淺談Vue.js》了解一下。
BootPage組件簡介
其實也不是啥高大上的組件了,相反確實一個簡單的表格分頁組件而已,主要是自己最近項目中需要一個表格分頁組件,而Vue官方組件庫里分頁組件都功能太強大或者沒有適合我的,所以就自己寫了一個湊合着用,或許有人和我一樣需要這樣一個簡單的分頁組件來實現簡單的分頁功能,我便在這里分享一下,大家自覺填坑咯。
如需高大上的組件,可以移步Vue官方組件庫:https://github.com/vuejs/awesome-vue#libraries--plugins
BootPage是一款支持靜態數據和服務器數據的表格分頁組件,支持調整每頁顯示行數和頁碼顯示個數,樣式基於bootstrap,就像這樣:
使用方法
在.vue的組件文件中我們這樣寫template,即html代碼:
<table class="table table-hover table-bordered"> <thead> <tr> <th width="10%">id</th> <th width="30%">name</th> <th width="40%">content</th> <th width="20%">remark</th> </tr> </thead> <tbody> <tr v-for="data in tableList"> <td v-text="data.num"></td> <td v-text="data.author"></td> <td v-text="data.contents"></td> <td v-text="data.remark"></td> </tr> </tbody> <tfoot> <tr> <td colspan="4"> <div class="col-sm-12 pull-right"> <boot-page :async="false" :data="lists" :lens="lenArr" :page-len="pageLen"></boot-page> </div> </td> </tr> </tfoot> </table>
<boot-page>標簽中async指是否從服務器端獲取數據,false為否;data為靜態的表格數據數組;lens為每頁顯示行數的數組;page-len為可顯示的頁碼數;
使用靜態數據的javascript代碼即script標簽內的內容如下:
<script> import bootPage from './components/BootPage.vue' export default { data () { return { lenArr: [10, 50, 100], // 每頁顯示長度設置 pageLen: 5, // 可顯示的分頁數 lists: [ {num: 1, author: 'luozh', contents: '123', remark: 'bootPage'}, {num: 1, author: 'luozh', contents: '123', remark: 'bootPage'}, {num: 1, author: 'luozh', contents: '123', remark: 'bootPage'}, {num: 1, author: 'luozh', contents: '123', remark: 'bootPage'}, {num: 1, author: 'luozh', contents: '123', remark: 'bootPage'}, {num: 1, author: 'luozh', contents: '123', remark: 'bootPage'} ], // 表格原始數據,使用服務器數據時無需使用 tableList: [] // 分頁組件傳回的分頁后數據 } }, components: { bootPage }, events: { // 分頁組件傳回的表格數據 'data' (data) { this.tableList = data } } } </script>
一般我們很少使用靜態的表格數據,大多數應用的數據都是從服務器端獲取的,所以這里提供了獲取服務器分頁數據的方法:
使用服務器數據的組件HTML如下:
<boot-page :async="true" :lens="lenArr" :url="url" :page-len="pageLen" :param="param"></boot-page>
其中url為服務器的請求地址;param為需要向服務器發送的參數對象;
使用服務器數據javascript的代碼如下:
<script> import bootPage from './components/BootPage.vue' export default { data () { return { lenArr: [10, 50, 100], // 每頁顯示長度設置 pageLen: 5, // 可顯示的分頁數 url: '/bootpage/', // 請求路徑 param: {}, // 向服務器傳遞參數 tableList: [] // 分頁組件傳回的分頁后數據 } }, methods: { refresh () { this.$broadcast('refresh') // 這里提供了一個表格刷新功能 } }, components: { bootPage }, events: { // 分頁組件傳回的表格數據(這里即為服務器傳回的數據) 'data' (data) { this.tableList = data } } } </script>
注:服務器除了傳給組件表格的數組內容,還需一個總頁數的鍵名,名為page_num
組件源碼
至於分頁的實現源碼這里的就不展示了,所有源碼我都上傳到了我的github,地址為:https://github.com/luozhihao/BootPage
這里事先提個醒:因為這個組件是我用幾個小時趕出來的,所以對於Vue組件的編寫格式和規范肯定是考慮不周的,沒有完全獨立出來,所以自覺填坑咯,這里只作分享。
當然你也可以隨意的修改組件的代碼來適合自己項目的使用,畢竟實現大而全的分頁組件還是比較復雜的。
收工,歡迎評論指正。
原創文章,轉載請注明來自一個蘿卜一個坑 -博客園[http://www.cnblogs.com/luozhihao]
本文地址:http://www.cnblogs.com/luozhihao/p/5516065.html
本文同步發表於:https://segmentfault.com/a/1190000005174322