项目需求如下图:
上代码:
<span class="line" style="margin-left:20px"></span>
<span class="font">分类标签信息</span>
<el-button
style="position: fixed;
right: 60px;
height: 34px;
background: #165DFF;
color: #FFFFFF;
font-size: 14px;"
@click="addGoods"
>
新增</el-button
>
<el-table :data="dataList" style="color: #202328;margin: 24px 20px;width:98%;" class="tableInput">
<el-table-column prop="name" label="标签名称" header-align="left" align="left">
<template slot-scope="scope">
<el-input v-model="scope.row.name" v-if="scope.row.status"> </el-input>
<span style="margin-left: 10px" v-else>{
{ scope.row.name }}</span>
</template>
</el-table-column>
<el-table-column prop="remark" label="备注信息" header-align="left" align="left">
<template slot-scope="scope">
<el-input v-model="scope.row.remark" v-if="scope.row.status"> </el-input>
<span style="margin-left: 10px" v-else>{
{ scope.row.remark }}</span>
</template>
</el-table-column>
<el-table-column :label="$t('handle')" fixed="right" header-align="left" align="left" width="120">
<template slot-scope="scope">
<el-button type="text" size="small" class="table-newBtn" @click="handleEdit(scope.row)">{
{
scope.row.status ? '保存' : '编辑'
}}</el-button>
<el-button type="text" size="small" class="table-newBtn" @click="deleteHandle(scope.row, scope.$index)">{
{
scope.row.status ? ' 取消' : '删除'
}}</el-button>
</template>
</el-table-column>
</el-table>
实现思路:通过一个status字段去判断当前是新增还是编辑,然后输入框和span标签按需展示
1、新增按钮逻辑:
定义一个名为arr的数组,设置当前数组的status和点击状态(clickType),然后将数据push到表格中
addGoods() {
let arr = {};
arr.name = '';
arr.remark = '';
arr.status = true;
arr.clickType = 'add';
this.dataList.push(arr);
},
2、编辑按钮逻辑:后边展示为保存和取消按钮,按钮的逻辑如下:
编辑的时候,在data中定义一个dataObj的对象去接收存储的旧数据
// 编辑和保存
handleEdit(row) {
// 方法一:新增字段判断
row.status = !row.status;
row.clickType = 'edit';
this.dataObj={...row}
},
//删除和取消
deleteHandle(row, index) {
var id = row.id;
// 取消逻辑
console.log(row, this.dataObj);
if (row.status) {
// 新增取消逻辑
if (row.clickType === 'add') {
this.dataList.splice(index, 1);
} else if (row.clickType === 'edit') {
row.name = this.dataObj.name;
row.remark = this.dataObj.remark;
}
row.status = false;
} else {
// if (this.mixinViewModuleOptions.deleteIsBatch && !id && this.dataListSelections.length <= 0) {
// return this.$message({
// message: this.$t('prompt.deleteBatch'),
// type: 'warning',
// duration: 500
// });
// }
this.$confirm('此操作将永久删除该数据,是否继续?', '是否删除', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
center: true
})
.then(() => {
this.$http
.delete(
`${this.mixinViewModuleOptions.deleteURL}${this.mixinViewModuleOptions.deleteIsBatch ? '' : '/' + id}`,
this.mixinViewModuleOptions.deleteIsBatch
? {
data: id ? [id] : this.dataListSelections.map(item => item['nodeId'])
}
: {}
)
.then(({ data: res }) => {
if (res.code !== 0) {
return this.$message.error(res.msg);
}
this.$message({
message: this.$t('prompt.success'),
type: 'success',
duration: 500,
onClose: () => {
this.query();
}
});
})
.catch(() => {});
})
.catch(() => {});
}
},