刚接了一个新需求  ,自定义表格的行和列,没有想到好的实现方法,就用原生table写了一个,直接上代码:

先给大家展示一下效果:

 下面直接上代码:

<el-button style="margin-left: 10px; float: right;" size="small" @click="refresh">重置</el-button>
<table>
      <template v-for="(item,index) in tableProDate">
          <tr>
            <template v-for="inx in cellLength">
              <td>
                <el-input style="width:100px;" v-model="item['tagCell'+''+inx]" size="small" :placeholder="item.placeholder" clearable> </el-input>
              </td>
           </template>
           <el-button v-if="index == 0" style="border-style: dashed;margin-top: 10px;" size="small"  @click="addCell()">添加列</el-button>
           <el-button v-else style="border-style: dashed;margin-top: 10px;" size="small" @click="delRow(index)">删除行</el-button>
          </tr>
        </template>
        <el-button style="border-style: dashed;margin-top: 10px" size="small" @click="addRow()">添加行</el-button>
      </table>

定义一个 tableProDate 数组,这个数组为整个表格的数据,tagCellObj为一行数据的对象,通过Object.keys(this.tagCellObj).length来获取对象的长度来进行列的添加操作。

 

export default {
    name: "performance",
    mixins: [dialogsMixins,inquiryMixins],
    data () {
      return {
        tagCellObj:{ 
          tagCell1:'',
        },
        tableProDate:[
          {
            tagCell1:'',
            placeholder:'表头内容'
          },
        ],
        cellLength:1,
      }
    },
    methods: {
      refresh(){  //重置
        this.cellLength = 1
        this.tableProDate.length = 0
         this.tableProDate.push({
            tagCell1:'',
            placeholder:'表头内容'
          })
        this.tagCellObj = {
          tagCell1:'',
        }
      },
      addRow(){   //添加行
        let param = Object.assign({},this.tagCellObj,{placeholder:'内容'})
        this.tableProDate.push(param)
      },
      delRow(index){  //删除行
        this.tableProDate.splice(index,1)
      },
      addCell(){   //添加列
        this.cellLength = Object.keys(this.tagCellObj).length +1
        if( this.cellLength==6){
          return
        }
         let lable = 'tagCell'+this.cellLength
        this.tableProDate.map((item,index)=>{
          this.$set(item,lable, '');
          if(index==0){
            item.placeholder = '表头内容'
          }else{
             item.placeholder = '内容'
          }
        })
        this.$set(this.tagCellObj,lable, '');
      }
    }
  }

如果有其他好的实现方法请推荐一下,继续学习。。。

 

 

Logo

前往低代码交流专区

更多推荐