Text-Input切換,失焦保存

需求

點(diǎn)擊文字,切換為Input,輸入后,失焦,保存數(shù)據(jù),切換為文字顯示

TIP
  1. 通過 isEditable 控制顯示
  2. 沒有數(shù)據(jù)的時(shí)候需要進(jìn)行占位
  3. 數(shù)據(jù)需要跟 form 進(jìn)行綁定,進(jìn)行校驗(yàn)
  4. 切換為 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>


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容