动态编辑表格(支持自定义编辑组件)
<template>
<div
class="edit-cell"
@click="onFieldClick"
>
<el-tooltip
v-if="!editMode && !showInput"
:placement="toolTipPlacement"
:open-delay="toolTipDelay"
>
<div
tabindex="0"
@keyup.enter="onFieldClick"
>
<slot name="content" />
</div>
</el-tooltip>
<component
:is="editableComponent"
v-if="editMode || showInput"
ref="input"
v-bind="$attrs"
v-model="model"
@focus="onFieldClick"
@keyup.enter.native="onInputExit"
v-on="listeners"
>
<slot name="edit-component-slot" />
</component>
</div>
</template>
<script>
export default {
name: "EditableCell",
inheritAttrs: false,
props: {
value: {
type: String,
default: ""
},
// toolTipContent: {
// type: String,
// default: this.value
// },
toolTipDelay: {
type: Number,
default: 5000000
},
toolTipPlacement: {
type: String,
default: "top-start"
},
showInput: {
type: Boolean,
default: false
},
editableComponent: {
type: String,
default: "el-input"
},
closeEvent: {
type: String,
default: "blur"
}
},
data() {
return {
editMode: false
};
},
computed: {
model: {
get() {
return this.value;
},
set(val) {
this.$emit("input", val);
}
},
listeners() {
return {
[this.closeEvent]: this.onInputExit,
...this.$listeners
};
}
},
methods: {
onFieldClick() {
this.editMode = true;
this.$nextTick(() => {
let inputRef = this.$refs.input;
if (inputRef) {
inputRef.focus();
}
});
},
onInputExit() {
this.editMode = false;
},
onInputChange(val) {
this.$emit("input", val);
}
}
};
</script>
<style>
</style>
- 在表格中使用时把渲染的内容放在content插槽中
<Editable-cell
v-model="row.companyLevel"
slot-scope="{ row }"
:show-input="row.editMode"
editable-component="el-select"
close-event="change"
></Editable-cell>
// 用插槽来把数据给到组件,使用的时候要记得给table绑定的数据加上是否显示编辑组件的值editMode,涉及到数据的保存修改时要把这个editMode删除掉,避免发起请求时作为不必要的字段传给接口
- 可以用map的方法把editMode添加到绑定数据中
mounted: async function () {
await this.getCompanyTable();
this.tableData = this.tableData.map(row => {
return {
...row,
editMode: false
};
});
},
标签:false,editMode,default,组件,input,type,String
From: https://www.cnblogs.com/domxia/p/17445291.html