单列修改
代码
<template>
<div class="app-container">
<el-table :data="tableData" border style="width: 60%">
<el-table-column
v-for="item of tableCol"
:key="item.key"
:label="item.label"
:prop="item.key"
:width="item.width"
>
<template #default="{ row, $index }">
<div v-if="item.key === 'address'">
<div v-if="addressEditIndex === $index">
<el-input
ref="addressInput"
v-model="row.address"
placeholder="请输入地址"
@blur="addressEditIndex = undefined"
@change="handleAddressUpdate(row)"
/>
</div>
<div v-else @click="handleAddressEdit($index)">{{ row.address || '无' }}</div>
</div>
<div v-else>{{ row[item.key] }}</div>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: 'Dashboard',
data() {
return {
tableCol: [
{ label: '姓名', key: 'name', width: 180 },
{ label: '日期', key: 'date', width: 180 },
{ label: '地址', key: 'address' }
],
tableData: [
{ date: '2016-05-02', name: '张三', address: '上海市普陀区金沙江路 1518 弄' },
{ date: '2016-05-04', name: '李四', address: '上海市普陀区金沙江路 1517 弄' },
{ date: '2016-05-01', name: '王五', address: '上海市普陀区金沙江路 1519 弄' }
],
addressEditIndex: undefined
}
},
methods: {
handleAddressUpdate(row) {
console.log(`更新行:${row}`)
},
handleAddressEdit(index) {
this.addressEditIndex = index
// 设置点击时自动获得焦点
this.$nextTick(() => {
this.$refs.addressInput[0].focus()
})
}
}
}
</script>
效果
多列修改
代码
<template>
<div class="app-container">
<el-table :data="tableData" border style="width: 60%">
<el-table-column
v-for="item of tableCol"
:key="item.key"
:label="item.label"
:prop="item.key"
:width="item.width"
>
<template #default="{ row, $index }">
<div v-if="editCell && item.key === editCell[0] && $index === editCell[1]">
<el-input
ref="cellInput"
v-model="row[item.key]"
:placeholder="`请输入${item.label}`"
@blur="editCell = undefined"
@change="handleAddressUpdate(editCell)"
/>
</div>
<div v-else @click="handleCellEdit(item.key, $index)">{{ row[item.key] || '无' }}</div>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: 'Dashboard',
data() {
return {
tableCol: [
{ label: '姓名', key: 'name', width: 180 },
{ label: '日期', key: 'date', width: 180 },
{ label: '地址', key: 'address' }
],
tableData: [
{ date: '2016-05-02', name: '张三', address: '上海市普陀区金沙江路 1518 弄' },
{ date: '2016-05-04', name: '李四', address: '上海市普陀区金沙江路 1517 弄' },
{ date: '2016-05-01', name: '王五', address: '上海市普陀区金沙江路 1519 弄' }
],
editCell: undefined
}
},
methods: {
handleAddressUpdate(editCell) {
console.log(`更新单元格:${editCell}`)
},
handleCellEdit(colKey, rowIndex) {
this.editCell = [colKey, rowIndex]
// 设置点击时自动获得焦点
this.$nextTick(() => {
console.log(this.$refs)
this.$refs.cellInput[0].focus()
})
}
}
}
</script>
效果