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

如何在Vue+TypeScript中定义与img元素一致的Props?

解决Vue3 TS自定义组件继承Img所有Props并实现类型推断的问题

错误原因

  • HTMLImageElement是DOM元素的实例类型,并非组件Props的属性类型,不能直接用于defineProps
  • 若导入ImgHTMLAttributes的路径或来源不正确,会导致类型无法解析

正确解决方案

步骤1:导入正确的属性类型

从@vue/runtime-dom导入ImgHTMLAttributes,这是Vue3中专门为HTML img元素定义的属性类型集合。

步骤2:在defineProps中使用该类型

直接将ImgHTMLAttributes作为defineProps的类型参数,Vue会自动完成所有img属性的类型推断。

完整代码示例

<script setup lang="ts">
import type { ImgHTMLAttributes } from '@vue/runtime-dom'

// 绑定img的所有属性类型
const props = defineProps<ImgHTMLAttributes>()
</script>

<template>
  <div>
    <!-- 自定义内容区域 -->
    <img v-bind="$attrs" />
  </div>
</template>

扩展用法(添加自定义属性)

如果需要给组件增加自定义属性,可以通过交叉类型扩展ImgHTMLAttributes:

interface CustomImgProps extends ImgHTMLAttributes {
  customTip?: string
}
const props = defineProps<CustomImgProps>()

内容的提问来源于stack exchange,提问作者João

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:52:06