這是 Element 網站的 table 示例:html
<template> <el-table :data="tableData" style="width: 100%"> <el-table-column prop="date" label="日期" width="180"></el-table-column> <el-table-column prop="name" label="姓名" width="180"></el-table-column> <el-table-column prop="address" label="地址"></el-table-column> </el-table> </template> <script> export default { data() { return { tableData: [{ date: '2016-05-02', name: '王小虎', address: '上海市普陀區金沙江路 1518 弄' }, { date: '2016-05-04', name: '王小虎', address: '上海市普陀區金沙江路 1517 弄' }, { date: '2016-05-01', name: '王小虎', address: '上海市普陀區金沙江路 1519 弄' }, { date: '2016-05-03', name: '王小虎', address: '上海市普陀區金沙江路 1516 弄' }] } } } </script>
上面的表格字段較少,代碼數量很少,可是當咱們在開發項目的時候,可能表格字段不少而且多處用到表格,那咱們的代碼量就會很是多並且冗雜,因此咱們須要進行二次封裝,從而精簡代碼量網站
按照暫時項目所需進行的二次封裝,遇到的問題以下:this
1. 爲表格添加序號列時,翻頁操做發現每一頁的序號都是從1開始spa
2. 操做列如何封裝/須要給某一個列自定義怎麼辦?code
問題一 可參考:https://www.cnblogs.com/langxiyu/p/10641060.htmlorm
問題二 關於操做列/自定義列我使用了 slot , 具體實現以下:
htm
封裝:blog
<template> <div class="data-table"> <el-table :data="tableData" style="width: 100%" border v-loading="loading"> <el-table-column label="序號" type="index" width="50" align="center"> <template scope="scope"> <!-- 有分頁時,序號顯示 --> <span v-if="pageObj">{{(pageObj.currentPage - 1)*pageObj.size + scope.$index + 1}}</span> <!-- 無分頁時,序號顯示 --> <span v-else>{{scope.$index + 1}}</span> </template> </el-table-column> <template v-for="(col, index) in columns"> <!-- 操做列/自定義列 --> <slot v-if="col.slot" :name="col.slot"></slot> <!-- 普通列 --> <el-table-column v-else :key="index" :prop="col.prop" :label="col.label" :width="col.width" :formatter="col.formatter" align="center"> </el-table-column> </template> </el-table> <!-- 是否調用分頁 --> <el-pagination v-if="pageObj" background layout="total, prev, pager, next, jumper" :page-size="pageObj.size" :total="pageObj.total" :current-page="pageObj.currentPage" @current-change="pageObj.func"> </el-pagination> </div> </template> <script> export default { name: "dataTable", props: ['tableData', 'columns', 'loading', 'pageObj'] } </script>
調用:排序
HTMLip
<lxy-table :tableData="tableData" :columns="columns" :loading="loading" :pageObj="pageObj"> <el-table-column slot="operate" label="操做" align="center" fixed="right" width="300"> <template slot-scope="scope"> <el-button size="small" type="warning" icon='el-icon-edit' @click="edit(scope.row)">編輯 </el-button> <el-button size="small" type="primary" icon='el-icon-success' @click="startUsing(scope.row)">啓用 </el-button> </template> </el-table-column> </lxy-table>
JS
tableData:[], columns: [ {label: '名稱', prop: 'adName'}, {label: '連接', prop: 'adUrl'}, {label: '排序', prop: 'sort'}, {slot: 'operate'}], // 操做列 loading: true, pageObj: { size: 10, total: 1, currentPage: 1, func:(currentPage) =>{ this.pageTurning(currentPage) } },
二次封裝解決,這樣執行每一個須要調用表格的地方代碼可操做性更強,代碼更加清晰明瞭!固然更多表格功能可自行再次添加~~~