HTML部分代码
<template>
<div>
<el-container>
<el-header>Header</el-header>
<el-main>
<div>
// 表格数据在这里: :data="tableData"
<el-table
border
:data="tableData"
class="tb-edit"
style="width: 100%"
highlight-current-row
@row-click="handleCurrentChange"
>
<el-table-column label="项目名称">
<template scope="scope">
<span>{{ scope.row.item }}</span>
</template>
</el-table-column>
// 动态循环表头数据
<el-table-column
:label="item.val"
v-for="(item,index) in tableHead"
:key="index"
>
<template scope="scope">
<el-input
size="small"
v-model="scope.row[item.item]"
placeholder="0"
type="number"
@change="handleEdit(scope.$index, scope.row,item.item)"
></el-input>
<span>{{ scope.row[item.item] }}</span>
</template>
</el-table-column>
<el-table-column label="总分" prop="total"> </el-table-column>
</el-table>
</div>
</el-main>
<el-footer> <el-button type="primary">提交</el-button></el-footer>
</el-container>
</div>
</template>
script部分代码
<script>
export default {
data() {
return {
// 表头数据
tableHead: [
{ val: "指标1", item: "target1" },
{ val: "指标2", item: "target2" },
{ val: "指标3", item: "target3" },
{ val: "指标4", item: "target4" },
{ val: "指标5", item: "target5" },
],
// 表格数据
tableData: [
{
item: "项目1",
target1: 0,
target2: 0,
target3: 0,
target4: 0,
target5: 0,
total: 0,
},
{
item: "项目2",
target1: 0,
target2: 0,
target3: 0,
target4: 0,
target5: 0,
total: 0,
},
{
item: "项目3",
target1: 0,
target2: 0,
target3: 0,
target4: 0,
target5: 0,
total: 0,
},
{
item: "项目4",
target1: 0,
target2: 0,
target3: 0,
target4: 0,
target5: 0,
total: 0,
},
{
item: "项目5",
target1: 0,
target2: 0,
target3: 0,
target4: 0,
target5: 0,
total: 0,
},
],
};
},
methods: {
// 合计
handleEdit(index, row) {
var sum = 0;
this.tableHead.forEach((element) => {
sum += Number(this.tableData[index][element.item]);
});
row.total = sum;
},
},
};
</script>
CSS部分代码(这里是实现可编辑的关键样式一定不能少)
<style lang="less">
* {
margin: 0;
padding: 0;
}
body {
font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
Microsoft YaHei, SimSun, sans-serif;
overflow: auto;
font-weight: 400;
-webkit-font-smoothing: antialiased;
}
.tb-edit .el-input {
display: none;
}
.tb-edit .current-row .el-input {
display: block;
}
.tb-edit .current-row .el-input + span {
display: none;
}
.el-table td,
.el-table th {
text-align: center !important;
}
</style>
效果图
这里实现的是点击可编辑,且在点击下一处任何地方,结尾自动合计总分,这里的数据是临时写的假数据(表头的项目名称和合计是写死的,因为它们对应的表格数据是不可编辑的,所以就写死了,循环的表头下面的数据都是可编辑的),后期大家可以把假数据注销,拿到后台接口,通过发送axios请求到后台数据,在渲染到前端页面即可。