ElementUI 表格可编辑单元格
2021-02-05 本文已影响0人
Cherry丶小丸子
页面
<div id="app">
<el-table :data="tableData">
<el-table-column prop="date" label="日期" width="180"></el-table-column>
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="address" label="地址">
<template slot-scope="scope">
<editable-cell :text="scope.row.address" @changeValue="onCellChange($event, scope.row)"></editable-cell>
</template>
</el-table-column>
</el-table>
</div>
<script>
export default{
components: {
EditableCell: () => import('@/components/EditableCell/EditableCell.vue'),
},
data() {
return {
tableData:[
{
date:"2020-12-01",
name:"my name is elementui",
address:"浙江省杭州市西湖区",
}
]
}
},
methods: {
onCellChange(val, row) {
// 将编辑之后的值 对应复制给 表格数据
row.address = val;
}
}
}
</script>
组件
<template>
<div class="editable-cell">
<div v-if="editable" class="editable-cell-input-wrapper">
<el-input class="editable-input" ref="editableInput" v-model="value" size="mini" @input="handleInput" @keyup.enter.native="check"></el-input>
<i class="editable-cell-icon-check el-icon-check" @click="check"></i>
</div>
<div v-else class="editable-cell-text-wrapper">
{{ value || ' ' }}
<i class="editable-cell-icon el-icon-edit" @click="edit"></i>
</div>
</div>
</template>
<script>
export default{
props: {
text: String,
},
data() {
return {
value: this.text,
editable: false,
}
},
methods: {
handleInput(e) {
const value = e;
this.value = value;
},
check() {
this.editable = false;
this.$emit('changeValue', this.value);
},
edit() {
this.editable = true;
this.$nextTick(() => {
this.$refs.editableInput.focus();
})
}
}
}
</script>
<style>
.editable-cell {
position: relative;
}
.editable-cell-input-wrapper,.editable-cell-text-wrapper {
padding-right: 24px;
height: 28px;
line-height: 28px;
}
.editable-cell-text-wrapper {
/* padding: 5px 24px 5px 5px; */
}
.editable-cell-input-wrapper .editable-input{
float: left;
}
.editable-cell-icon,.editable-cell-icon-check {
position: absolute;
top:0;
bottom:0;
right: 0;
margin:auto;
cursor: pointer;
}
.editable-cell-icon {
width:16px;
height:16px;
line-height: 16px;
text-align: center;
display: none;
}
.editable-cell-icon-check {
width:16px;
height:16px;
line-height: 16px;
text-align: center;
}
.editable-cell:hover .editable-cell-icon {
display: inline-block;
}
.editable-cell-icon:hover,.editable-cell-icon-check:hover {
color: #108ee9;
}
</style>