如何在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
相关产品推荐
相关产品推荐

