一、在行数据中设置一个属性,用来区分当前行或者当前列是否在进行修改,使用v-show实现
- 在行内添加button,并直接操作当前数据对象,变更其值用来控制当前行或当前列是否修改,注意看几个button的click事件
- 如果在表格外部使用按钮操作,则定义一个method,传递行数据在table原始数据中的index,在method中操作对应index的数据。
<template>
<div>
<el-table :data="list">
<el-table-column align="center" label="编号" width="80">
<template slot-scope="{ row }">
<span v-show="!row.editid">{{ row.id }}</span>
<el-input v-show="row.editid" v-model="row.id"></el-input>
</template>
</el-table-column>
<el-table-column width="180px" label="名称">
<template slot-scope="{ row }">
<span v-show="!row.editname">{{ row.name }}</span>
<el-input v-show="row.editname" v-model="row.name"></el-input>
</template>
</el-table-column>
<el-table-column align="center" label="操作" width="300">
<template slot-scope="{ row }">
<el-button
v-show="!row.editid"
type="primary"
size="mini"
icon="el-icon-edit"
@click="row.editid = !row.editid"
>
编辑id
</el-button>
<el-button
v-show="!row.editname"
type="primary"
size="mini"
icon="el-icon-edit"
@click="row.editname = !row.editname"
>
编辑名称
</el-button>
<el-button
v-show="row.editid || row.editname"
type="success"
size="mini"
icon="el-icon-circle-check-outline"
@click="(row.editid = false) || (row.editname = false)"
>
Ok
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: "growth",
data() {
return {
list: [
{ id: "1", name: "法外狂徒", editid: false, editname: false },
{ id: "2", name: "张三", editid: false, editname: false },
],
};
},
};
</script>
<style lang="scss" scoped></style>>
二、使用el-table自带的class来判断是否显示输入框,主要使用css实现
- el-table需要添加highlight-current-row="true",这样在点击某一行时,会将其设置为选中状态,并在dom节点上添加current-row类
- 如果需要清除或者变更某一行的选中状态,则使用el-table本身的setCurrentRow方法,细节见官方文档
<template>
<div>
<el-button @click="ok" type="success">确认</el-button>
<el-table :data="list" highlight-current-row ref="mytb">
<el-table-column align="center" label="编号" width="80">
<template slot-scope="{ row }">
<span>{{ row.id }}</span>
<el-input v-model="row.id"></el-input>
</template>
</el-table-column>
<el-table-column width="180px" label="名称">
<template slot-scope="{ row }">
<span>{{ row.name }}</span>
<el-input v-model="row.name"></el-input>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: "growth",
data() {
return {
list: [
{ id: "1", name: "法外狂徒" },
{ id: "2", name: "张三" },
],
};
},
methods: {
ok() {
this.$refs.mytb.setCurrentRow();
},
},
};
</script>
<style lang="scss" scoped>
.el-table {
// 默认情况下,即没有选中某一行时,只显示span
span {
display: block;
}
.el-input {
display: none;
}
// 当点击某一行时,对应的行会添加current-row类,则内部的新的样式会生效
.current-row {
span {
display: none;
}
.el-input {
display: block;
}
}
}
</style>
三、两种方法的比较
- 方法1比较灵活,可以精准控制到每一个行的每一个列,但是要多写一些v-show和对应的变更方法。
- 方法2代码简单,编写好css,基本不需要在html中注意这部分的操作,但是相对的不灵活一些,一次性控制一整行,无法控制到列