在Vue中,创建一个可编辑的树状表格并实施版本对比功能是一种需求较为常见的场景。在本教程中,我们将使用Vue结合Element UI的el-table组件,来构建一个树状表格,其中包含添加、编辑功能,并通过特定的方法展示数据变更。本文会详继解析每一步的代码实现。
图中,黄色为修改的数据,绿色为新增,红色是被删除的数据。

首先,我们使用el-table组件创建基础的表格,并通过tree-props属性指定了如何展示树形数据的结构。
<template>
<div class="h-station">
<el-card class="h-card">
<el-button type="primary" @click="addScheme">添加一级分类el-button>
<el-button type="primary">批量导入el-button>
<el-table
:data="tableData"
:row-class-name="getRowClass"
style="width: 100%; margin-top: 15px"
border
height="calc(100vh - 260px)"
row-key="id"
:tree-props="{ children: 'children' }">
<el-table-column align="center" prop="name" label="维修方案名称" min-width="100px">
<template slot-scope="scope">
<el-input
v-if="scope.row.type !== 'Button'"
style="width: calc(100% - 50px)"
v-model="scope.row.name"
:disabled="scope.row.type === 'delete'">
el-input>
template>
el-table-column>
el-table>
el-card>
div>
template>
在data函数中定义的tableData数组,包含了表格数据和结构信息。此外,我们会备份原始数据以供版本对比之用。
<script>
export default {
data() {
return {
rawData: [],
tableData: [...],
curMateral: { children: [] },
materials: [],
materialsTypeIds: [],
materialsTypeNames: [],
};
},
created() {
this.rawData = JSON.parse(JSON.stringify(this.tableData));
this.loadMaterialsInfo(); // 模拟加载物料信息
},
methods: {
enrichDataWithLevel(data, level = 1, parent = null) {
return data.map(item => ({
...item,
level,
children: item.children ? this.enrichDataWithLevel(item.children, level + 1, item) : [],
parent,
}));
},
// 示例方法:模拟加载物料信息
loadMaterialsInfo() {
this.materials = [{ materialsTypeId: 1, materialsTypeName: '物料1' }];
this.curMateral = this.materials[0];
},
}
};
</script>
我们通过getRowClass方法为表格行动态赋予样式,标识数据的更改状态:新添加、更改或删除。
methods: {
getRowClass({ row, rowIndex }) {
let rawNode = this.findNodeById(this.rawData, row.id);
if (row.type === 'delete') {
return 'deleted-row';
} else if (row.id.includes && row.id.includes('cwx-') && row.type !== 'Button') {
return 'new-row';
} else if (rawNode) {
let flag = true;
if (rawNode&&!(row.id+'').includes('cwx-')) {
let keys = Object.keys(rawNode);
keys.push('materialsTypeIds')
for (let key of keys) {
if(key==='materialsTypeIds'){
if((!rawNode.materialsTypeIds||rawNode.materialsTypeIds.length===0)&&(!row.materialsTypeIds||row.materialsTypeIds.length===0)){
}else{
flag=false
}
}
else if (rawNode[key] !== row[key]&&(key!=='parent')&&(key!=='children')) {
flag = false;
}
}
}
if(!flag){
return 'change-row';
}
}
},
}
使用SCSS来定义不同状态下行的样式:
添加一级分类
批量导入
添加子方案
--
{{
getMaterialsNameStr(getMaterialsName(scope.row.materialsTypeIds || []))
}}
撤销删除
关联物料
删除
保存更改
返回
通过这种方式,我们不仅提供了树状表格数据的编辑功能,还实现了通过颜色和样式标识不同版本之间数据变动的可视化展示。这使得数据的对比和审核变得直观和高效。