You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue点击搜索图标触发Illegal invocation错误:focus调用对象非HTMLElement

解决“illegal invocation”及focus调用错误

问题原因

直接将$refs.searchInput.focus作为点击事件回调时,focus方法的上下文(this)会丢失,不再指向input元素本身,导致调用时触发“illegal invocation”错误;如果组件尚未完成挂载,$refs.searchInput可能为undefined,还会出现“'focus' called on an object that does not implement interface HTMLElement.”的提示。

修复方案

方案1:用箭头函数包裹调用

修改模板中的点击事件,通过箭头函数确保focus方法的this指向input元素:

<div class="search-wrap">
  <input
    ref="searchInput"
    v-model="searchData"
    type="text"
    class="form-control search-input not-as-small"
    placeholder="Search by name"
    @input="inputSearchValue"
  >
    <i
      class="search-strong search-input-icon"
      @click.prevent="() => $refs.searchInput.focus()"
    />
</div>

方案2:定义组件方法处理

在组件的methods中添加一个方法,统一处理聚焦逻辑,同时用可选链操作符避免ref未挂载的情况:

methods: {
  inputSearchValue() {
    // 原有逻辑
  },
  focusSearchInput() {
    this.$refs.searchInput?.focus()
  }
}

然后修改模板中的点击事件绑定:

<div class="search-wrap">
  <input
    ref="searchInput"
    v-model="searchData"
    type="text"
    class="form-control search-input not-as-small"
    placeholder="Search by name"
    @input="inputSearchValue"
  >
    <i
      class="search-strong search-input-icon"
      @click.prevent="focusSearchInput"
    />
</div>

内容的提问来源于stack exchange,提问作者smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:30:10