useImage
在浏览器中响应式加载图像,您可以等待结果显示或显示备用图像。
演示
加载中...
用法
vue
<script setup>
import { useImage } from '@vueuse/core'
const avatarUrl = 'https://place.dog/300/200'
const { isLoading } = useImage({ src: avatarUrl })
</script>
<template>
<span v-if="isLoading">Loading</span>
<img v-else :src="avatarUrl">
</template>
组件用法
此函数还通过
@vueuse/components
包提供了无渲染组件版本。了解更多关于用法的信息。
vue
<template>
<UseImage src="https://place.dog/300/200">
<template #loading>
Loading..
</template>
<template #error>
Failed
</template>
</UseImage>
</template>
类型声明
显示类型声明
typescript
export interface UseImageOptions {
/** Address of the resource */
src: string
/** Images to use in different situations, e.g., high-resolution displays, small monitors, etc. */
srcset?: string
/** Image sizes for different page layouts */
sizes?: string
/** Image alternative information */
alt?: string
/** Image classes */
class?: string
/** Image loading */
loading?: HTMLImageElement["loading"]
/** Image CORS settings */
crossorigin?: string
/** Referrer policy for fetch https://mdn.org.cn/en-US/docs/Web/HTTP/Headers/Referrer-Policy */
referrerPolicy?: HTMLImageElement["referrerPolicy"]
/** Image width */
width?: HTMLImageElement["width"]
/** Image height */
height?: HTMLImageElement["height"]
/** https://mdn.org.cn/en-US/docs/Web/HTML/Element/img#decoding */
decoding?: HTMLImageElement["decoding"]
/** Provides a hint of the relative priority to use when fetching the image */
fetchPriority?: HTMLImageElement["fetchPriority"]
/** Provides a hint of the importance of the image */
ismap?: HTMLImageElement["isMap"]
/** The partial URL (starting with #) of an image map associated with the element */
usemap?: HTMLImageElement["useMap"]
}
/**
* Reactive load an image in the browser, you can wait the result to display it or show a fallback.
*
* @see https://vueuse.org.cn/useImage
* @param options Image attributes, as used in the <img> tag
* @param asyncStateOptions
*/
export declare function useImage<Shallow extends true>(
options: MaybeRefOrGetter<UseImageOptions>,
asyncStateOptions?: UseAsyncStateOptions<Shallow>,
): UseAsyncStateReturn<HTMLImageElement | undefined, any[], true>
export type UseImageReturn = ReturnType<typeof useImage>
源码
贡献者
更新日志
v12.8.0
on 3/5/2025v12.3.0
on 1/2/202559f75
- feat(toValue): 弃用来自 @vueuse/shared
的 toValue
,转而使用 Vue 原生方法v12.2.0-beta.1
on 12/23/2024v12.0.0-beta.1
on 11/21/2024v10.2.0
on 6/16/2023v10.1.1
on 5/1/2023v10.0.0-beta.4
on 4/13/20234d757
- feat(types)!: 将 MaybeComputedRef
重命名为 MaybeRefOrGetter
0a72b
- feat(toValue): 将 resolveUnref
重命名为 toValue