element input组件自动失去焦点问题解决

最近在 Vue3 + ElementPlus 中,使用 el-input 组件时,如果设置了 v-model,那么在每次改变内容后后,input 会自动失去焦点,这样会导致用户无法输入多个字符。

一、问题原因

如上图所示,配置项的 Name 和 Code 都是使用 el-input 组件 v-for 遍历渲染的,都绑定了 v-model,而 :key 绑定的是对应的 Code 值。

所以,当 Code 改变后,当前所在的节点 key 值也改变了,根据 Vue 的 diff 算法,key 值改变后会导致节点重新渲染,这也就会导致 Code 在每输入一个字符后,input 自动失去焦点。

二、解决方案

解决方案很简单,只需要将 :key 绑定的值改为 index 即可,因为 index 对于当前这一组节点是不变的。

代码演示:

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>

欢迎访问:天问博客

相关推荐
泓博7 小时前
npm包冲突install失败
npm·vue
海的诗篇_9 小时前
前端开发面试题总结-vue3框架篇(一)
前端·css·vue.js·面试·vue·html
一只不会编程的猫9 小时前
Could not find a declaration file for module ‘..XX‘.
linux·前端·vue.js·前端框架·vue·es6
风吹一夏v13 小时前
webpack到vite的改造之路
webpack·vue·vite
BillKu17 小时前
vue3 + TypeScript +Element Plus 输入框回车事件 @keydown.enter
vue.js·elementui·typescript
Luffe船长1 天前
vue+elementUI实现固定table超过设定高度显示下拉条
前端·elementui·vue
ew452181 天前
【VUE】某时间某空间占用情况效果展示,vue2+element ui实现。场景:会议室占用、教室占用等。
前端·vue.js·ui·elementui
BillKu2 天前
Element Plus 对话框 el-dialog 和 抽屉 el-drawer 的使用注意项(使用 div 包裹)
javascript·vue.js·elementui
海的诗篇_3 天前
前端开发面试题总结-vue2框架篇(四)
前端·css·面试·vue·html
全栈小53 天前
【前端】Vue3+elementui+ts,给标签设置样式属性style时,提示type check failed for prop,再次请出DeepSeek来解答
前端·elementui