需求
點(diǎn)擊文字,切換為Input,輸入后,失焦,保存數(shù)據(jù),切換為文字顯示
TIP
- 通過 isEditable 控制顯示
- 沒有數(shù)據(jù)的時(shí)候需要進(jìn)行占位
- 數(shù)據(jù)需要跟 form 進(jìn)行綁定,進(jìn)行校驗(yàn)
- 切換為 Input 后需要手動(dòng)設(shè)置 focus,保證初次失焦就可以進(jìn)行校驗(yàn)
<!-- editable input實(shí)現(xiàn)方案 -->
<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="請(qǐng)輸入"
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("文字點(diǎn)擊", 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('有報(bào)錯(cuò): ', err)
})
};
</script>
<style lang="less" scoped></style>