elementUI Table表格内容可编辑,效果如图:
- 大体思路
采用div替代template标签,包裹input和div(if-else控制显示隐藏)。
在table表格绑定 "鼠标双击" 事件用于单元格编辑,同时input框绑定 "失焦" 事件用于调取接口修改信息。(注:使用自定义指令,双击单元格时自动获取焦点)
使用“render-header" 重新渲染表头(js控制),添加提示信息。
<template>
<el-table :data="tableData" v-loading="loading" max-height="730" @cell-dblclick="handleCellEnter" >
<el-table-column label="姓名" prop="nurseName" width="200px" align="center" :render-header="renderHeader">
<div class="item" slot-scope="scope">
<el-input v-if="scope.row.NameInputShow" v-focus class="itemInput" placeholder="请输入姓名" maxlength="20" v-model="scope.row.Name" @blur="NameBlur(scope.row)">
</el-input>
<div v-else class="itemTxt">{{scope.row.Name}}</div>
</div>
</el-table-column>
<el-table-column label="手机号" prop="Phone" width="200px" align="center" :render-header="renderHeader">
<div class="item" slot-scope="scope">
<el-input v-if="scope.row.PhoneInputShow" v-focus class="itemInput itemPhone" placeholder="请输入手机号" v-model="scope.row.Phone" maxlength="11" @blur="PhoneBlur(scope.row)">
</el-input>
<div v-else class="itemTxt">{{scope.row.Phone}}</div>
</div>
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
// 需要编辑得属性
editProp: ["Name", "Phone"],
};
},
directives: {
focus: {
inserted: function (el) {
el.querySelector("input").focus();
},
},
},
methods: {
/** 获取数据时给每条数据添加字段 用于控制input框的显示隐藏 */
async initData() {
const { body } = await this.$request();
if (body?.list) {
body.list.map((item) => {
this.$set(item, "NameInputShow", false);
this.$set(item, "PhoneInputShow", false);
});
},
/**鼠标双击cell */
handleCellEnter(row, column, cell, event) {
let property = column.property;
if (property === "Name") {
row.NameInputShow = true;
}
if (property === "Phone") {
row.PhoneInputShow = true;
}
},
/** 失去焦点调取后台接口修改信息,并刷新列表 */
PhoneBlur(item) {
this.editNurseNameOrPhone(item);
},
NameBlur(item) {
this.editNurseNameOrPhone(item);
},
/** js控制 重新渲染列头信息 */
renderHeader(h, { column }) {
return h("div", [
h("span", column.label + " "),
h(
"el-tooltip",
{
props: {
effect: "light",
content: "双击此列内容可修改",
placement: "top",
},
},
[
h("i", {
class: "el-icon-info",
}),
]
),
]);
},
},
};
</script>
<style scoped>
/* 样式可根据自己情况修改 */
.item {
height: 50px;
line-height: 50px;
}
.itemInput {
width: 70%;
}
.itemPhone {
width: 150px;
}
.itemTxt {
min-width: 20px;
min-height: 50px;
}
</style>