这是 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) } },
二次封装解决,这样执行每一个须要调用表格的地方代码可操做性更强,代码更加清晰明了!固然更多表格功能可自行再次添加~~~