需求
在el-table中想要直接點(diǎn)擊單元格直接由文字顯示變?yōu)榫庉嬁驙顟B(tài)表锻,而非一整行編輯或者通過展示模態(tài)框編輯,這樣目標(biāo)性會比較清楚且頁面較簡潔乞娄。下面直接上代碼瞬逊!
html代碼
<template>
<!-- table表格內(nèi)行內(nèi)編輯input、日期組件等 -->
<div id="app">
<!-- @cell-dblclick="tableDbEdit" 當(dāng)單元格被雙擊擊時會觸發(fā)tableDbEdit事件仪或,將文字變成input輸入框,也可以使用單擊事件@cell-click=''-->
<el-table ref="table" :data="tableList" border style="width: 100%" @cell-dblclick="tableDbEdit">
<!-- 編輯input組件-->
<el-table-column prop="name" label="工作名稱">
<template slot-scope="scope">
<!-- 條件判斷如果滿足則顯示表單确镊,否則默認(rèn)展示文字 -->
<el-input v-model="scope.row.name" v-if="showInput == `name${scope.row.id}`"
@blur='blurInput(scope.row.id,"name",scope.row.name)' v-focus>
</el-input>
<p v-else>{{scope.row.name}}</p>
</template>
</el-table-column>
<!-- 編輯日期組件-->
<el-table-column prop="planStartTime" label="預(yù)計開始" align="center">
<template v-slot="scope">
<el-date-picker v-model="scope.row.planStartTime" v-if="showInput == `planStartTime${scope.row.id}`"
type="date" :clearable="false" value-format="yyyy-MM-dd" placeholder="請選擇開始日期"
@blur='blurInput(scope.row.id,"planStartTime",scope.row.planStartTime)' v-focus>
</el-date-picker>
<p v-else>{{scope.row.planStartTime}}</p>
</template>
</el-table-column>
</el-table>
</div>
</template>
js代碼
<script>
export default {
data() {
return {
//表格數(shù)據(jù)
tableList: [
{
id: 0,
name: "規(guī)劃許可階段",
planStartTime: "2021-03-09"
},
{
id: 1,
name: "施工許可階段",
planStartTime: "2021-03-09"
}
],
showInput: "",
oldData: {}
}
},
directives: {
// 通過自定義指令實現(xiàn)的表單自動獲得光標(biāo)的操作
focus: {
inserted: function(el) {
if (el.tagName.toLocaleLowerCase() == "input") {
el.focus()
} else {
if (el.getElementsByTagName("input")) {
el.getElementsByTagName("input")[0].focus()
}
}
el.focus()
}
},
focusTextarea: {
inserted: function(el) {
if (el.tagName.toLocaleLowerCase() == "textarea") {
el.focus()
} else {
if (el.getElementsByTagName("textarea")) {
el.getElementsByTagName("textarea")[0].focus()
}
}
el.focus()
}
}
},
// 方法
methods: {
// 當(dāng)input失去光標(biāo)后進(jìn)行的操作
async blurInput(id, name, value) {
let obj = {}
// 判斷數(shù)據(jù)是否有所改變,如果數(shù)據(jù)有改變則調(diào)用修改接口
if (this.oldData[name] != value) {
obj[name] = value //被改變的數(shù)據(jù)
// 然后再寫調(diào)用接口范删,提交內(nèi)容的東西就可以了
console.log("===值改變了")
}
this.showInput = ""
},
/*
方法參數(shù)皆為框架方法的默認(rèn)傳參
row 行數(shù)據(jù)
column 被點(diǎn)擊的觸發(fā)了方法的單元格
event 事件
*/
tableDbEdit(row, column, event) {
this.showInput = column.property + row.id
this.oldData[column.property] = row[column.property]
}
}
}
</script>