el-input 中回车指令意外触发了其他组件的函数
前言
组件嵌套如下(有点奇怪吧🤣):
el-scrollbar
el-form
global-setting
trans-setting
recognize
history-record
在开发轻译的历史记录搜索功能时,遇到了很奇怪的问题,莫名其妙出现了自动触发TransSetting组件中的speedTest方法,但是在我在HistoryRecord组件中并没有调用该方法,调试半天😅😅😅。
后面问了GPT,似乎是原生button的问题,GPT建议将之改为span,故而解决问题。
解决
TransSetting 组件
<el-input
class="config-google-url"
:model-value="googleUrl"
placeholder="请输入谷歌翻译地址"
clearable
@focus="getServerList"
@input="emit('update:googleUrl', $event)"
>
<template #append>
<button class="primary-btn" @click="speedTest">测试</button>
</template>
</el-input>
将button标签改为span标签
<span class="primary-btn" @click="speedTest">测试</span>
WHY
以下便是ChatGPT的回答
🎯 为什么按回车会触发 <template #append> 中的按钮?
你的 <el-input> 包含:
<template #append>
<button class="primary-btn" @click="speedTest">测试</button>
</template>
这部分在渲染出来后,实际上是一个嵌在输入框右侧的 <button> 标签。
按下 回车 键时,如果当前焦点在 <input> 上,而页面结构中紧邻有一个 button 元素,浏览器有可能把回车解释为提交表单或激活该按钮。
尤其在以下情况容易出现:
- 按钮是
<button>元素而非<span>或<div>等伪按钮。 - 包裹在
<form>或<el-form>中时。 - 浏览器默认行为未禁用时。

浙公网安备 33010602011771号