el-table动态添加列

本文介绍如何在Vue.js项目中使用ElementUI实现表格动态添加列的功能。内容包括从后端获取JSON字符串解析成动态列,遍历custom字段生成列,DOM渲染动态列,以及添加和删除列的操作。最后,展示了处理数据生成后端所需的custom JSON字符串的代码,以实现高可配置性的表格功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发管理系统过程中碰到一些需求,针对表格,运营人员需要自己添加一些列,然后输入内容保存,以此来实现产品的高可配性,接下来我们就来实现这个功能。

对于这些动态添加的列,后端用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);
            this.dynamicColumns.push({ prop: key, label: key});
          }
        })
      }else{
        item.custom = {};
      }
})

这样就可以得到dynamicColumns为[ { prop: "测试", label: "测试" },  { prop: "字段2", label: "字段2" } ]

 

2、然后我们在DOM里渲染出动态列:

3、点击“添加列”按钮,就往this.dynamicColumns中push一个新的列;点击表头的删除,就splice掉,以此来实现列的增加和删除

addColumn() {
      this.$prompt("请输入列名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
        this.dynamicColumns.push({
          prop: value,
          label: value
        });
      });
},
deleteColunm(index) {
      this.dynamicColumns.splice(index, 1);
},

4、点击“提交”按钮时,我们处理一下数据,生成和后端返回时那样的custom的JSON字符串,过滤掉空值:

submit() {
      let arr = [];
      this.tableData.forEach(data => {
        let temp = {};
        temp.name = data.name; // 这里改成后端要求的id即可
        let obj = {};
        this.dynamicColumns.forEach(col => {
          // 仅把有效的列提交
          if (data.custom[col.prop]) {
            obj[col.prop] = data.custom[col.prop];
          }
        });
        if (JSON.stringify(obj) !== "{}") {
          temp.custom = JSON.stringify(obj);
        }
        arr.push(temp);
      });
}

 

这样就实现了动态配置列和相应字段值的功能,完整的vue代码如下:

<template>
  <div class="custom-table">
    <el-button type="primary" size="mini" @click="addColumn">添加列</el-button>
    <el-button type="primary" size="mini" @click="submit">提交</el-button>
    <el-table :data="tableData" border style="width: 100%" ref="myTable">
      <el-table-column prop="date" label="日期" width="180"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="180"> </el-table-column>
      <el-table-column prop="address" label="地址"> </el-table-column>

      <!-- 动态列 -->
      <el-table-column
        v-for="(item, index) in dynamicColumns"
        :key="index"
        :prop="item.prop"
      >
        <template slot="header">
          {{ item.label }}
          <i
            class="el-icon-remove"
            style="color:red;cursor:pointer;"
            @click="deleteColunm(index)"
          ></i>
        </template>
        <template slot-scope="scope">
          <el-input
            v-if="isEdit"
            v-model="scope.row.custom[item.prop]"
            placeholder="请输入内容"
          ></el-input>
          <span v-else>{{ scope.row.custom[item.prop] }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "CustomTable",
  data() {
    return {
      isEditHeader: false,
      isEdit: true,
      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}"
        }
      ],
      propArr:[], // 生成dynamicColumns时的记录
      dynamicColumns: [] // 存放动态列
    };
  },
  created(){
    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);
            this.dynamicColumns.push({ prop: key, label: key});
          }
        })
      }else{
        item.custom = {};
      }
    })
  },
  methods: {
    addColumn() {
      this.$prompt("请输入列名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
        this.dynamicColumns.push({
          prop: value,
          label: value
        });
      });
    },
    deleteColunm(index) {
      this.dynamicColumns.splice(index, 1);
    },
    submit() {
      let arr = [];
      this.tableData.forEach(data => {
        let temp = {};
        temp.name = data.name;
        let obj = {};
        this.dynamicColumns.forEach(col => {
          // 仅把有效的列提交
          if (data.custom[col.prop]) {
            obj[col.prop] = data.custom[col.prop];
          }
        });
        if (JSON.stringify(obj) !== "{}") {
          temp.custom = JSON.stringify(obj);
        }
        arr.push(temp);
      });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss"></style>

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值