el-table 實現(xiàn)單元格內(nèi)編輯功能
功能
雙擊單元格出現(xiàn)編輯框谓娃,編輯框失去焦點后保存內(nèi)容柬焕。
原理
- 通過
v-if
控制編輯框與顯示值顯示和隱藏欣硼。 - 通過
el-table
組件·的cell-dblclick
事件骑冗,得到row秉宿、column
的數(shù)據(jù)疙剑,并且顯示編輯框氯迂,隱藏顯示值。 - 通過
el-input
組件的blur
隱藏編輯框言缤。
步驟
1.顯示編輯框嚼蚀,聚焦編輯框
顯示編輯框
column.property
是當前的template
中el-table-column
所填寫的property
值
row[column.property + "isShow"] = true
table
數(shù)據(jù)改動時,給table
的key
值一個隨機數(shù)轧简,刷新table
驰坊。
this.randomKey = Math.random()
編輯框聚焦
this.$nextTick
是為了確保ref
存在后執(zhí)行下列代碼
this.$nextTick(() => {
this.$refs[column.property] && this.$refs[column.property].focus()
})
2.編輯框失去焦點,隱藏編輯框
row[column.property + "isShow"] = false
完整代碼
<template>
<div>
<el-table :data="items"
:key="randomKey"
@cell-dblclick="editData"
style="width: 100%">
<el-table-column label="日期"
property="date"
width="140">
<template slot-scope="scope">
<el-input v-if="scope.row[scope.column.property + 'isShow']"
:ref="scope.column.property"
v-model="scope.row.date"
@blur="alterData(scope.row,scope.column)"></el-input>
<span v-else>{{ scope.row.date }}</span>
</template>
</el-table-column>
<el-table-column label="順序"
property="id"
width="140">
<template slot-scope="scope">
<el-input v-if="scope.row[scope.column.property + 'isShow']"
:ref="scope.column.property"
v-model="scope.row.id"
@blur="alterData(scope.row,scope.column)"></el-input>
<span v-else>{{ scope.row.id }}</span>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data () {
return {
items: [
{ date: '2016-05-03', id: '0' },
{ date: '2016-05-04', id: '1' },
{ date: '2016-05-05', id: '2' },
{ date: '2016-05-06', id: '3' },
],
randomKey: Math.random(),
}
},
methods: {
editData (row, column) {
row[column.property + "isShow"] = true
//refreshTable是table數(shù)據(jù)改動時哮独,刷新table的
this.refreshTable()
this.$nextTick(() => {
this.$refs[column.property] && this.$refs[column.property].focus()
})
},
alterData (row, column) {
row[column.property + "isShow"] = false
this.refreshTable()
},
refreshTable () {
this.randomKey = Math.random()
},
}
}
</script>