在开发管理系统过程中碰到一些需求,针对表格,运营人员需要自己添加一些列,然后输入内容保存,以此来实现产品的高可配性,接下来我们就来实现这个功能。
对于这些动态添加的列,后端用JSON字符串的形式存储起来最为方便,这里我们假定存储在custom字段中,例如:custom: "{\"测试\": 1}" 这种形式。
所以我们的el-table中,一部分为固有表头字段,而动态列则通过数组循环生成。
1、首先假设返回的表格数据为:
tableData: [
{
date: "2016-05-02",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
custom: ""
},
{
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
custom: "{\"测试\": 1}"
},
{
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
custom: "{\"测试\": 1, \"字段2\": \"哈哈哈\"}"
},
{
date: "2016-05-03",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
custom: "{\"测试\": 1}"
}
],
这里我们要遍历custom字段得到到底有哪几个动态列,并将字符串转为JSON对象,所以拿到数据后我们要处理一下:
this.tableData.forEach(item=>{
if(item.custom){
item.custom = JSON.parse(item.custom);
Object.keys(item.custom).forEach(key => {
if(this.propArr.indexOf(key) === -1){
this.propArr.push(key);