指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

js关于click事件问题:

<Input
                  v-model="option.name"
                  placeholder="Meal option"
                  @focus="onInputFocus(index)"
                  @blur="onInputBlur"
                  @keydown.enter="onKeyDown(index, option.name, $event)"
                  class="[&_.common-field\_\_input]:!h-[2.125rem]"
                />
<Icon name="delete" size="sm" class="bg-brand-subtlest rounded cursor-pointer absolute -right-6" v-if="currentInput > 0 && currentInput === index && isFocused" @click="clickInputForm"/>

当input获得焦点的时候, 后面的删除icon会展示,当失去焦点的时候,icon会隐藏,但是当我点击icon的时候,也会触发input失去焦点,然后icon的点击事件没法触发.

这是一个常见的问题,原因是当点击 delete 图标时,input 的失去焦点事件 (blur) 被触发,导致图标被隐藏,同时图标的点击事件没有机会执行。

解决方法

为了防止 blur 事件导致 icon 无法触发点击事件,可以使用 mousedown 事件代替 click,因为 mousedown 事件发生在 blur 事件之前,这样可以先处理删除图标的点击逻辑。


修改后的代码
<Input
  v-model="option.name"
  placeholder="Meal option"
  @focus="onInputFocus(index)"
  @blur="onInputBlur"
  @keydown.enter="onKeyDown(index, option.name, $event)"
  class="[&_.common-field\_\_input]:!h-[2.125rem]"
/>
<Icon
  name="delete"
  size="sm"
  class="bg-brand-subtlest rounded cursor-pointer absolute -right-6"
  v-if="currentInput > 0 && currentInput === index && isFocused"
  @mousedown="clickInputForm"
/>

关键点
  1. 使用 @mousedown 代替 @click:

    • mousedown 事件在 blur 事件之前触发,可以在 input 的失焦之前处理图标的逻辑。
  2. 保持逻辑一致性:

    • 在删除逻辑完成后,blur 逻辑依然有效,不会受到干扰。

补充:更精细的控制(防止失焦逻辑)

如果希望在 icon 点击时完全阻止 blur 逻辑,可以通过 preventDefault 方法来实现:

<Input
  v-model="option.name"
  placeholder="Meal option"
  @focus="onInputFocus(index)"
  @blur="onInputBlur"
  @keydown.enter="onKeyDown(index, option.name, $event)"
  class="[&_.common-field\_\_input]:!h-[2.125rem]"
/>
<Icon
  name="delete"
  size="sm"
  class="bg-brand-subtlest rounded cursor-pointer absolute -right-6"
  v-if="currentInput > 0 && currentInput === index && isFocused"
  @mousedown="preventBlur($event)"
  @click="clickInputForm"
/>
methods: {
  preventBlur(event) {
    // 阻止失焦
    event.preventDefault();
  },
  clickInputForm() {
    // 删除逻辑
    console.log("Icon clicked");
  },
}

两种方案对比
  1. 使用 @mousedown 替代 @click:

    • 简单有效,适合大多数场景。
    • 无需显式阻止 blur 事件,逻辑清晰。
  2. 使用 event.preventDefault():

    • 提供更精细的控制,适合复杂场景。
    • 需要手动阻止 blur,可能会引入额外逻辑。

推荐根据实际需求选择合适的方法。目前使用的是第一种方法,当然第二种方法也是可以的。