实现效果
![](https://i-blog.csdnimg.cn/blog_migrate/ceb5acf4da25d025eb03fc507fa2a5aa.png)
调用方式
<EditableListItem
v-for="(remark, index) in listData"
:item="remark"
:key="remark.remarkId"
@change="newVal => handleItemChange(newVal, remark)"
@delete="handleItemDelete(remark)"
/>
组件代码
<template>
<div class="edit-item">
<div class="edit-box">
<div class="content">
<div v-if="editable" class="editable-cell-input-wrapper">
<a-textarea :value="value" @change="handleChange" maxlength="300" @pressEnter="check" />
</div>
<div v-else class="editable-cell-text-wrapper">
<span>{{ value || ' ' }}</span>
</div>
</div>
<div class="btn-group">
<template v-if="editable">
<a-icon type="check" class="editable-cell-icon-check" @click="check" />
<a-divider type="vertical"></a-divider>
<a-icon type="close-circle" class="editable-cell-icon" @click="cancel" />
</template>
<template v-else>
<a-icon type="edit" class="editable-cell-icon" @click="edit" />
<a-divider type="vertical"></a-divider>
<a-icon type="delete" class="editable-cell-icon" @click="handleDelete" />
</template>
</div>
</div>
<div class="description">
<span>句段: {{ item.segmentId }} </span>
<span style="margin-left: 15px">添加时间: {{ item.createTime }} </span>
<span style="margin-left: 15px">添加人: {{ item.createBy }}</span>
</div>
</div>
</template>
<script>
export default {
name: 'EditableListItem',
props: {
item: {
type: Object,
default: () => ({
segmentId: 1,
remark: 'test',
createBy: 'admin',
createTime: '2022-06-20 10:37:16'
})
}
},
watch: {
item: {
deep: true,
handler(newVal) {
this.init();
}
}
},
data() {
return {
value: '',
editable: false,
originalVal: ''
};
},
created() {
this.init();
},
methods: {
init() {
this.value = '' + this.item.remark;
this.originalVal = '' + this.item.remark;
},
handleChange(e) {
this.value = e.target.value;
},
check() {
this.editable = false;
this.$emit('change', this.value);
},
edit() {
this.editable = true;
},
handleDelete() {
this.editable = false;
this.$emit('delete');
},
cancel() {
console.log('取消了本次更改');
console.log(this.value);
this.value = '' + this.originalVal;
this.editable = false;
}
}
};
</script>
<style scoped>
.edit-item {
margin-bottom: 10px;
border: 1px solid rgba(0, 0, 0, 0.3);
position: relative;
}
.edit-box {
width: 100%;
overflow: hidden;
}
.content {
padding: 10px;
margin-right: 60px;
}
.btn-group {
position: absolute;
right: 0;
top: 0;
padding: 5px;
}
.description {
background: #f6f6f6;
padding: 5px;
font-size: 12px;
color: grey;
}
.editable-cell-text-wrapper {
word-wrap: break-word;
word-break: normal;
white-space: normal;
}
</style>