Skip to content

useImage

类别
导出体积
1.11 kB
上次更改
3 weeks ago

响应式加载浏览器中的图像,你可以等待结果以显示它,或显示一个备用图像。

示例

Loading...

使用方法

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">加载中</span>
  <img v-else :src="avatarUrl">
</template>

组件使用

vue
<template>
  <UseImage src="https://place.dog/300/200">
    <template #loading>
      加载中..
    </template>

    <template #error>
      加载失败
    </template>
  </UseImage>
</template>

类型声明

显示类型声明
typescript
export interface UseImageOptions {
  /** 资源的地址 */
  src: string
  /** 不同情况下使用的图片,例如高分辨率显示器、小型监视器等 */
  srcset?: string
  /** 不同页面布局的图片尺寸 */
  sizes?: string
  /** 图片的替代信息 */
  alt?: string
  /** 图片的类名 */
  class?: string
  /** 图片的加载方式 */
  loading?: HTMLImageElement["loading"]
  /** 图片的跨域设置 */
  crossorigin?: string
  /** 获取者策略用于获取资源 */
  referrerPolicy?: HTMLImageElement["referrerPolicy"]
  /** Image width */
  width?: HTMLImageElement["width"]
  /** Image height */
  height?: HTMLImageElement["height"]
  /** https://developer.mozilla.org/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/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>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
btea
Jelf
Riley Gelwicks
François M
vaakian X
Lúcio Rubens

更新日志

v12.3.0 on 1/2/2025
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
v12.2.0-beta.1 on 12/23/2024
4ca72 - feat: support more native option (#4173)
v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v10.2.0 on 6/16/2023
04d32 - feat: support referrerPolicy option (#3132)
v10.1.1 on 5/1/2023
c110a - feat: support more image properties (#3021)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
0a72b - feat(toValue): rename resolveUnref to toValue
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)