最近在做后台管理项目,列表table显示是家常便饭,很多时候一个页面里面会有好几个table,如果使用常规的书写,html代码实在太长了,而且不同的列表里需要出现相同的用户信息,会造成代码的冗余,使用下面的方法可以有效的解决代码不优雅的部分
1、首先需要确定table内部的样式html
activeStatus选中tabs的值,不同列表接口可能不同
columns是数据的展示字段
<el-table :data="logList" border> <template v-for="(item, index) in columns[activeStatus]"> <el-table-column :key="index" :fixed="item.fixed" :prop="item.field" :label="item.title" :align="item.align ? item.align : 'center'" :min-width="item.width"> <template slot-scope="scope"> <div class="display-flex" v-if="item.type=='vhtml'" v-html="item.formatter(scope.row)"></div> <div v-if="item.type=='vtext'">{{scope.row[item.field]}}</div> </template> </el-table-column> </template> </el-table>
2、然后确定字段,return字段的样式
let formatterHtml = { order_id: (row) => { return `${row.order.id}` }, order_sn: (row) => { return `${row.order.order_sn}` }, time: (row) => { return `${moment(row.createtime*1000).format('YYYY-MM-DD HH:mm:ss')}` }, user_message: (row) => { return `<div class="display-flex" style="justify-content: flex-start;width: 100%;"> <div style="width:36px;height:36px;border: 1px solid #E6E6E6;border-radius: 2px;margin-right:10px"> <el-image src="${Fast.api.cdnurl(row.buyer.avatar)}" fit="contain"> <div slot="error" class="image-slot"> <i class="el-icon-picture-outline"></i> </div> </el-image> </div> <div>${row.buyer.nickname}</div> </div>` }, }
columns: { 'order': [{ type: 'vhtml', field: '', title: 'ID', width: '70px', formatter: formatterHtml.order_id, }, { type: 'vhtml', field: '', title: '订单号', width: '220px', formatter: formatterHtml.order_sn, }, { type: 'vhtml', field: '', title: '下单用户信息', width: '160px', formatter: formatterHtml.user_message, }, { type: 'vhtml', field: '', title: '加入时间', width: '160px', formatter: formatterHtml.time, }], },
这样子写可以提高字段的灵活性,希望对你可以有所帮助。😁