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

Vue3+TypeScript项目中如何为$refs指定非any类型避免eslint警告

替代any的类型方案

方案1:预先声明$refs类型(推荐,可获得完整类型提示)

首先根据你target绑定的对象类型,扩展组件实例的$refs类型定义:

  • 若target绑定的是原生DOM元素(如div、input等):
import type { ComponentPublicInstance } from 'vue';

// 扩展全局组件实例的$refs类型
declare module '@vue/runtime-core' {
  interface ComponentPublicInstance {
    $refs: {
      // 是具体元素可替换为对应类型,比如HTMLInputElement
      target: HTMLElement 
    }
  }
}

声明后可直接访问,无需额外断言:

const el = this.$refs.target
  • 若target绑定的是自定义Vue子组件:
import type { ComponentPublicInstance } from 'vue';
// 导入你的子组件
import ChildComponent from './ChildComponent.vue';

declare module '@vue/runtime-core' {
  interface ComponentPublicInstance {
    $refs: {
      target: InstanceType<typeof ChildComponent>
    }
  }
}

访问$el的写法如下,完全符合TS规则:

const el = this.$refs.target.$el as HTMLElement

方案2:单次临时断言(无需修改全局类型)

如果只是单次使用不想做全局声明,可以直接替换any为对应类型:

  • 原生元素场景:
const el = this.$refs['target'] as HTMLElement
  • 自定义组件场景,不知道子组件类型时可用通用组件实例类型:
import type { ComponentPublicInstance } from 'vue'

const el = (this.$refs['target'] as ComponentPublicInstance).$el as HTMLElement

知道子组件类型时可以写得更精确:

const el = (this.$refs['target'] as InstanceType<typeof ChildComponent>).$el as HTMLElement

提示:Vue的ref仅在组件挂载完成后才会被赋值,建议访问时增加可选链操作符?.避免运行时报错,比如this.$refs.target?.$el。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:15:08