ElementUI对于表格的二次封装
前言
最近在做的项目中,有大量界面用到了表格(el-table)组件,但是里面具体显示的内容不同,是从后端获取过来的,如果每一个界面写一下el-table的代码的话,会造成代码量大且不易维护的后果,所以就对el-table表格进行了二次封装。
过程
先看一下最终效果
代码实现
1.抽出来的子组件的代码:
<template>
<div>
<!-- 表格部分 -->
<el-table :data="tableData" stripe border :default-sort="{prop: 'date', order: 'descending'}">
<!-- 表格业务内容列 -->
<template v-for="(item, index) in tableOption">
<el-table-column
:key="index"
:prop="item.prop"
:label="item.label"
:align="item.align || 'center'"
:show-overflow-tooltip="item.overHidden || false"
:min-width="item.width || '100px'"
:fixed="item.fixed || true"
:sortable="item.sortable || false"
:type="item.type || 'normal'"
></el-table-column>
</template>
<!-- 表格操作列 -->
<el-table-column label="操作" v-if="isOperate" min-width="150px">
<template slot-scope="scope">
<slot name="operate" :row="scope.row"></slot>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {};
},
// 父组件向子组件传值
props: {
// 表格显示的数据
tableData: {
type: Array,
default: function() {
return [];
}
},
// 表格的操作
tableOption: {
type: Array,
default: function() {
return [];
}
},
// 控制操作列是否显示
isOperate: {
type: Boolean,
default: function() {
return false;
}
}
},
methods: {}
};
</script>
<style>
</style>
2.父组件中对子组件的引用
①引入子组件
import commonTable from "../../components/table/common-table";
②注册子组件
components: {
commonTable
},
③覆用子组件
<common-table :tableData="tableData" :tableOption.sync="tableOption" :isOperate="isOperate">
<!-- 操作列,填充operate的插槽 -->
<template slot="operate" slot-scope="scope">
<!-- 具体要显示的按钮可以在这里自定义 -->
<el-button type="primary" size="mini">查看</el-button>
</template>
</common-table>
// 表格数据
tableData: [
{
id: 1,
title: "林业信息拉萨解放了书法家",
status: "APPROVAL_PENDING",
docAuthor: "zhangshan",
submitTime: "2020-06-06 23:58:49"
},
{
id: 2,
title: "林业信息拉萨解放了书法家",
status: "DRAFT",
docAuthor: "zhangshan",
submitTime: "2020-06-07 00:10:59"
},
{
id: 6,
title: "林业信息拉萨解放了书法家",
status: "APPROVAL_PENDING",
docAuthor: "zhangshan",
submitTime: "2020-06-11 08:07:26"
}
],
// 表格操作
tableOption: [
{
type: "selection",
label: "#"
},
{
prop: "title",
label: "稿件名称",
overHidden: true
},
{
prop: "status",
label: "稿件状态",
sortable: true
},
{
prop: "docAuthor",
label: "作者"
},
{
prop: "submitTime",
label: "提交日期",
sortable: true
}
],
// 控制操作列是否显示
isOperate: true,
API属性
小结
对于elementUI表格的二次封装目前封到了这个程度,这样,如果其他界面有需要使用表格的,直接覆用子组件,然后传递表格数据就可以了,代码量会减少一大部分,而且对比起来也易于维护。
还没有评论,来说两句吧...