> 文章列表 > elementUI-el-table组件使用总结

elementUI-el-table组件使用总结

elementUI-el-table组件使用总结

一、背景

vue2项目中用到el-table这个组件,但基础的功能不够用,所以需要自定义

二、表头自定义

比如要让表头展现出下面的形式:

 只需使用 slot="header" slot-scope="scope" 对插槽进行定义,并绑定变量

<el-table>    <el-table-column><template slot="header" slot-scope="scope"><el-inputv-model="search"placeholder="输入关键字搜索"/></template></el-table-column>
</el-table>data() {return {search: ''}
},

三、表格内容自定义

有时除了对表头要做定制外,对表格内容也需要做定制,比如按照表格值是0or1来显示不同的内容等。

3.1对表格数据做二次处理

一个经典例子就是时间戳格式的转换(后端传回来的数据往往不是xxxx-xx-xx这种形式)。

只需给 el-table-column 的 formatter 属性绑定一个自己写的函数即可,比如下面这样:

<el-table-column prop="Start" :formatter="dateFormat"  label="开始时间"></el-table-column>
dateFormat(row, column) {const date = row[column.property]if (date === null || date === undefined) {return '<null>'}return date
},

3.2改变表格内容的展示形式

只需在列标签内部定义 slot-scope="scope"这个插槽然后写入自定义内容即可

<el-table :data="tableData" border stripe style="width: 100%"><el-table-column prop="name" label="类名" width="180"></el-table-column><el-table-column prop="icon" label="图标" width="180"><template slot-scope="scope"><i :class="scope.row.icon"></i></template></el-table-column>
</el-table><script>
export default {data() {return {tableData: [{name: '图标1',icon: 'fa fa-camera-retro',},{name: '图标2',icon: 'fa fa-camera-retro2',},]}}
}
</script>

上述代码效果如下:

 3.3内容中插入图片

和3.2的做法类似,不过这里需要注意要使用 :src 这种写法(绑定变量而非字符串)

<el-table-column prop="img" label="图片"><template v-slot="scope"><img :src="scope.row.img" width="90" height="90"></template>
</el-table-column>data() {return {imgs: [{img: require('@/assets/images/views/login-logo1.png') },{img: require('@/assets/images/views/login-logo2.png') }, {img: require('@/assets/images/views/login-logo3.png') },]}
}