Part.1 為什么要二次封裝?
這是 Element 網站的 table 示例:
<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>
上面的表格字段較少,代碼數量不多,但是當我們在開發項目的時候,可能表格字段很多並且多處用到表格,那我們的代碼量就會非常多而且冗雜,所以我們需要進行二次封裝,從而精簡代碼量
Part.2 遇到的問題
按照暫時項目所需進行的二次封裝,遇到的問題如下:
1. 為表格添加序號列時,翻頁操作發現每一頁的序號都是從1開始
2. 操作列如何封裝/需要給某一個列自定義怎么辦?
Part.3 解決
問題一 可參考:https://www.cnblogs.com/langxiyu/p/10641060.html
問題二 關於操作列/自定義列我使用了 slot , 具體實現如下:
封裝:
<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>
調用:
HTML
<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) } },
二次封裝解決,這樣執行每個需要調用表格的地方代碼可操作性更強,代碼更加清晰明了!當然更多表格功能可自行再次添加~~~