需求
点击文字,切换为Input,输入后,失焦,保存数据,切换为文字显示
TIP
- 通过 isEditable 控制显示
- 没有数据的时候需要进行占位
- 数据需要跟 form 进行绑定,进行校验
- 切换为 Input 后需要手动设置 focus,保证初次失焦就可以进行校验
<!-- editable input实现方案 -->
<template>
<span v-show="!isEditable" @click="clickText" style="display: inline-block;background: pink; width: 100%;height: 100%;">{{ formValue?.value }}</span>
<a-form v-show="isEditable" ref="formRef" :model="formValue" :wrapper-col="{ span: 24 }">
<a-form-item ref="value" required label="" name="value">
<a-input ref="targetElementRef" @blur="formItemBlur" v-model:value="formValue.value" placeholder="请输入"
autocomplete="off" :maxlength="64" />
</a-form-item>
</a-form>
</template>
<script setup lang="ts">
import { ref, nextTick } from "vue";
const formRef = ref()
const formValue = ref<{ value?: string }>({})
const targetElementRef = ref()
const isEditable = ref<boolean>(false)
const clickText = async (e) => {
console.log("文字点击", e);
isEditable.value = !isEditable.value
await nextTick()
targetElementRef.value.focus()
};
const formItemBlur = (e) => {
console.log("文本框失焦", e, formRef.value.value, formValue.value);
formRef.value.validate().then(() => {
isEditable.value = !isEditable.value
}).catch((err) => {
console.log('有报错: ', err)
})
};
</script>
<style lang="less" scoped></style>