elementUI Table表格內(nèi)容可編輯,效果如圖:
- 大體思路
采用div替代template標(biāo)簽澳淑,包裹input和div(if-else控制顯示隱藏)历等。
在table表格綁定 "鼠標(biāo)雙擊" 事件用于單元格編輯序宦,同時(shí)input框綁定 "失焦" 事件用于調(diào)取接口修改信息。(注:使用自定義指令为狸,雙擊單元格時(shí)自動(dòng)獲取焦點(diǎn))
使用“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="請(qǐng)輸入姓名" 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="手機(jī)號(hào)" 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="請(qǐng)輸入手機(jī)號(hào)" 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: {
/** 獲取數(shù)據(jù)時(shí)給每條數(shù)據(jù)添加字段 用于控制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);
});
},
/**鼠標(biāo)雙擊cell */
handleCellEnter(row, column, cell, event) {
let property = column.property;
if (property === "Name") {
row.NameInputShow = true;
}
if (property === "Phone") {
row.PhoneInputShow = true;
}
},
/** 失去焦點(diǎn)調(diào)取后臺(tái)接口修改信息辐棒,并刷新列表 */
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: "雙擊此列內(nèi)容可修改",
placement: "top",
},
},
[
h("i", {
class: "el-icon-info",
}),
]
),
]);
},
},
};
</script>
<style scoped>
/* 樣式可根據(jù)自己情況修改 */
.item {
height: 50px;
line-height: 50px;
}
.itemInput {
width: 70%;
}
.itemPhone {
width: 150px;
}
.itemTxt {
min-width: 20px;
min-height: 50px;
}
</style>