公共表格封装
<template>
<el-table :data="datas" :span-method="spanMethod" @selection-change="select" :default-sort="sort" stripe>
<template v-for="(config, index) in config">
<slot v-if="config.slot" :name="config.slot"></slot>
<el-table-column
v-bind="config"
:resizable="false"
:key="index"
height="20"
></el-table-column>
</template>
</el-table>
</template>
<script>
export default {
name: "mergeTable",
props: {
datas: {// 数据
type: Array,
required: true,
default: () => [],
},
config: {// 表头
type: Array,
required: true,
default: () => [],
},
mergeKeys: {// 合并
type: Array,
default: () => [],
},
select:{// 多选
type:Function,
default:()=>{}
},
sort:{// 排序
type:Object,
default:()=>{}
}
},
data() {
return {mergeData: {},
mergePos: {},};
},
mounted() {this.getSpanArr(this.datas, this.mergeKeys);
},
methods: {getSpanArr(tableData, keyName) {const [mergeData, mergePos] = [this.mergeData, this.mergePos];
keyName.forEach((kitem) => {tableData.forEach((data, i) => {if (i === 0) {mergeData[kitem] = mergeData[kitem] || [];
mergeData[kitem].push(1);
mergePos[kitem] = 0;
} else {if (data[kitem] === tableData[i - 1][kitem]) {mergeData[kitem][mergePos[kitem]] += 1;
mergeData[kitem].push(0);
} else {mergeData[kitem].push(1);
mergePos[kitem] = i;
}
}
});
});
},
spanMethod({row, column, rowIndex, columnIndex}) {if (this.mergeKeys.includes(column.property)) {const _row = this.mergeData[column.property][rowIndex];
const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col,
};
}
},
},
};
</script>
组件中应用
<mergeTable
:config="tableConfig"
:datas="list"
:select="handleSelectionChange"
:sort="{prop:'update_at', order:'descending'}"
>
<el-table-column slot="select" type="selection" width="50" align="center" />
<el-table-column slot="name" label="名称" align="center">
<template slot-scope="{row}"></template>
</el-table-column>
<el-table-column slot="owner" label="运维负责人" align="center">
<template slot-scope="{row}"></template>
</el-table-column>
</mergeTable>
data(){
return {
tableConfig:[{ prop: "select", slot: "select"},
{prop: "name", slot: "name"},
{prop: "business", slot: "business"},
{prop: "developer", slot: "developer"},
{prop: "owner", slot: "owner"},
{prop: "tester", slot: "tester"},
{prop: "update_at", label: "最近拜访", sortable:"sortable",align: "center"},
]
}
}