最近在 Vue3 + ElementPlus 中,使用 el-input
組件時,如果設(shè)置了 v-model
,那么在每次改變內(nèi)容后后,input 會自動失去焦點,這樣會導(dǎo)致用戶無法輸入多個字符。
一、問題原因
如上圖所示,配置項的 Name 和 Code 都是使用 el-input
組件 v-for
遍歷渲染的,都綁定了 v-model
,而 :key
綁定的是對應(yīng)的 Code 值。
所以,當(dāng) Code 改變后,當(dāng)前所在的節(jié)點 key
值也改變了,根據(jù) Vue 的 diff
算法,key 值改變后會導(dǎo)致節(jié)點重新渲染,這也就會導(dǎo)致 Code 在每輸入一個字符后,input 自動失去焦點。
二、解決方案
解決方案很簡單,只需要將 :key
綁定的值改為 index
即可,因為 index 對于當(dāng)前這一組節(jié)點是不變的。
代碼演示:文章來源:http://www.zghlxwxcb.cn/news/detail-789035.html
<template>
<div
v-for="(item, index) in form.config"
:key="index"
class="flex items-center mb-5px p-10px pl-50px"
>
<div class="m-5px color-#999">Name:</div>
<el-input class="w-139px" v-model="item.value" placeholder="請輸入" />
<div class="color-#999 m-5px">Code:</div>
<el-input class="w-139px" v-model="item.key" placeholder="請輸入" />
<el-button
@click="delConfig({ ...item, index })"
link
class="ml-10px"
:disabled="form.config.length <= 1"
>
<el-icon size="16" color="#409eff"><IEpDelete /></el-icon>
</el-button>
<el-button
link
class="ml-10px"
v-if="form.config.length - 1 === index"
@click="addConfig"
>
<el-icon size="16" color="#409eff"><IEpPlus /></el-icon>
</el-button>
</div>
</template>
歡迎訪問:天問博客文章來源地址http://www.zghlxwxcb.cn/news/detail-789035.html
到了這里,關(guān)于element input組件自動失去焦點問題解決的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!