element table动态增加列及动态表头

个人记录 方便查阅

<template>
  <div>
      <p>{{cols}}</p>
    <el-table :data="tableData" style="width: 100%" :key="itemKey">
      <el-table-column label="Date" prop="date"> </el-table-column>
      <el-table-column label="Name" prop="name"> </el-table-column>
      <el-table-column label="address" prop="address"> </el-table-column>
      <el-table-column v-for="(col, index) in cols" :key="index" align="right">
        <template slot="header" slot-scope="scope">
          <el-input
            v-if="colsIndex === index"
            v-model="col.title"
            size="mini"
            placeholder="输入表头"
          />
          <span v-if="colsIndex !== index">{{ cols[index].title }}</span>
        </template>
        <template slot-scope="scope">
          <span>增加的动态内容</span>
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >Edit</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-button raw-type="button" @click="addCol">
      添加一列
    </el-button>
    <el-button raw-type="button" @click="deleteCol">
      删除一列
    </el-button>
  </div>
</template>

<script>
export default {
  name: "FormTable",
  data() {
    return {
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄"
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄"
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄"
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄"
        }
      ],
      cols: [{ title: "" }],
      colsIndex: 0,
      itemKey:null // 强制让表格刷新一次
    };
  },
  computed: {},
  watch: {},
  methods: {
    addCol() {
      this.cols.push({ title: "" });
      this.colsIndex = this.cols.length - 1;
      console.log("增加的值", this.cols);
      this.itemKey = Math.random()

    },
    deleteCol() {
        /** 
         * bug 数据更新了 页面没更新数据 table拿到的数据还是以前的老数据,采用了给table加个key的方法解决
         * 让 table 重新加载 然后刷新数据
        */
        const data = JSON.parse(JSON.stringify(this.cols));
        data.splice(data.length - 2, 1);
        console.log("删除后的值", this.cols);
        this.$set(this,'cols',data)
        this.colsIndex = this.cols.length - 1;
        this.itemKey = Math.random()
    },
    handleEdit(index, row) {
      console.log(index, row);
    }
  }
};
</script>

<style scoped lang="less"></style>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值