先上效果图:
需求:
1.动态循环后端返回的表头 以及 表格数据
2.鼠标悬浮动态列 显示key:value
3.编辑table里的 单元格
动态循环表头
因为是后端返回表头数组 固用不了render 只能换种方式用slot动态循环显示表头 具体如下
<Table :no-data-text="$t('common.noData')" :columns="tableColumns" :data="tableData" border @on-sort-change="sortChange">
<!-- 资源ID -->
<template slot-scope="{ row }" slot="resourceId">{{ row.resourceId }}</template>
<!-- 动态循环的tag -->
<template slot-scope="{ row,column,index }" :slot="item.slot" v-for="(item,index) in tableColumns.slice(1)">
<!-- 编辑单元格 -->
<Input v-model="tableData[index][column.slot]" v-if="selectedCell.rowIndex === index && selectedCell.columnIndex === column.slot" @on-enter="initSelectedCell(row,tableData[index][column.slot],item.slot)" icon="ios-close-circle" @on-click="clickIcon"/>
<!-- 显示内容 -->
<div v-else>
<Tooltip :content="row.tag" :transfer="true" max-width="200">
<div @click="editCellData(row,column,index)" :style="((row[item.slot]!='') ?'cursor: pointer;':'width: 200px;padding:10px 10px 10px 0px;cursor: pointer;')" >{{ row[item.slot] }}</div>
</Tooltip>
</div>
</template>
</Table>
初始化参数
selectedCell: 定位行和列数据
tableColumns: 后端返回表头内容数组
tableData: 后端返回表格内容数组
data() {
return {
selectedCell:{
columnIndex:'',
rowIndex:''
},
tableColumns: [
{
title:"资源ID",
slot: "resourceId"
},
{
title: "tag1",
slot: "aaa",
sortable: true,
key:"aaa"
},
{
title: "tag2",
slot: "bbb",
sortable: true,
key:"bbb"
},
{
title: "tag3",
slot: "ccc",
sortable: true,
key:"ccc"
}],
tableData: [
{
id:0,
resourceId:'资源ID1',
aaa:'a',
bbb:'test1',
ccc:'测试1',
tag:'key:value'
},
{
id:1,
resourceId:'资源ID2',
aaa:'b',
bbb:'test2',
ccc:'测试2',
tag:'key:value'
},{
id:2,
resourceId:'资源ID3',
aaa:'c',
bbb:'test3',
ccc:'测试3',
tag:'key:value'
},{
id:3,
resourceId:'资源ID4',
aaa:'d',
bbb:'test4',
ccc:'测试4',
tag:'key:value'
},{
id:4,
resourceId:'资源ID5',
aaa:'e',
bbb:'test5',
ccc:'测试5',
tag:'key:value'
}]
}
},
方法
// 关闭Input框
clearInput:function(){
this.selectedCell.rowIndex='';
this.selectedCell.columnIndex='';
},
//输入框回车事件 大家可根据自己逻辑自行修改该方法逻辑
initSelectedCell:function(){
// 单元格数据不输入给默认值
let columnData = this.selectedCell.columnIndex;
let rowData = this.selectedCell.rowIndex;
if (this.tableData[rowData][columnData] == null || this.tableData[rowData][columnData] == '') {
this.tableData[rowData][columnData] = 0;
}
this.selectedCell.rowIndex='';
this.selectedCell.columnIndex='';
},
//编辑单元格
editCellData:function(row,column,index){
this.selectedCell.rowIndex = index;
this.selectedCell.columnIndex = column.slot;
},
// 排序
sortChange:function(){
this.clearInput();
},
// 点击图标
clickIcon:function(){
this.clearInput();
this.getTableResourceTagData();
},