前言
最近在做的項目中,有大量界面用到了表格(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表格的二次封裝目前封到了這個程度,這樣,如果其他界面有需要使用表格的,直接覆用子組件,然後傳遞表格數據就可以了,代碼量會減少一大部分,而且對比起來也易於維護。