Image
Adds loading placeholders, error content, lazy loading, and large-image previews to native <img>. Use HuiImageViewer to open a viewer separately.
Import
import { HuiImage, HuiImageViewer } from '@nscode/handy-ui'
Basic usage
Pass the image URL as src. width and height accept pixel numbers or CSS strings, such as '50%'. If only width is set, height follows the image aspect ratio.
<script setup lang="ts">
import { HuiImage, HuiSpace } from '@nscode/handy-ui'
</script>
<template>
<HuiSpace wrap align="start">
<HuiImage src="/images/cat.jpg" alt="A cat" :width="200" :height="150" />
<HuiImage src="/images/cat.jpg" alt="Width only" width="120px" />
</HuiSpace>
</template>
Object fit
fit controls how the image fits its container, with the same values as CSS object-fit. The default is 'fill'. These examples place a 4:3 image in a 100×100 square; the gray background belongs to the container:
fill: stretches to fill the container, distorting the image.contain: shows the entire image while preserving its ratio, leaving space above and below.cover: fills the container while preserving its ratio, cropping the sides.none: uses the original image size, so only its center is visible.scale-down: chooses the smaller result ofnoneandcontain. Since this image is larger than the square, it matchescontain.
<script setup lang="ts">
import { HuiImage, HuiSpace } from '@nscode/handy-ui'
import type { ImageProps } from '@nscode/handy-ui'
const fits: NonNullable<ImageProps['fit']>[] = ['fill', 'contain', 'cover', 'none', 'scale-down']
</script>
<template>
<HuiSpace wrap size="large">
<HuiSpace v-for="fit in fits" :key="fit" direction="vertical" align="center">
<HuiImage src="/images/cat.jpg" :fit="fit" :width="100" :height="100" class="box" />
<span class="caption">{{ fit }}</span>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.box {
background-color: var(--hui-fill-color);
}
.caption {
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Rounded images
round applies border-radius: 50%. Equal width and height produce a circle; unequal dimensions produce an ellipse.
<script setup lang="ts">
import { HuiImage, HuiSpace } from '@nscode/handy-ui'
</script>
<template>
<HuiSpace wrap align="center">
<HuiImage src="/images/avatar.jpg" round :width="80" :height="80" />
<HuiImage src="/images/avatar.jpg" round :width="48" :height="48" />
<HuiImage src="/images/cat.jpg" round fit="cover" :width="120" :height="80" />
</HuiSpace>
</template>
Loading and errors
Loading shows a spinner by default. Failure shows localized error text. placeholder and error can provide image URLs, or use their namesake slots; slots take precedence.
<script setup lang="ts">
import { HuiImage } from '@nscode/handy-ui'
</script>
<template>
<HuiImage
src="/images/big.jpg"
placeholder="/images/loading.png"
error="/images/broken.png"
:width="200"
:height="150"
/>
</template>
The first invalid URL below displays the default loading error. The second also fails, then displays the image provided by error:
<script setup lang="ts">
import { HuiImage, HuiSpace } from '@nscode/handy-ui'
</script>
<template>
<HuiSpace wrap>
<HuiImage src="/broken.png" :width="160" :height="120" />
<HuiImage
src="/broken.png"
error="/images/empty.png"
fit="contain"
:width="160"
:height="120"
/>
</HuiSpace>
</template>
Changing src restores the loading state until the new image loads or fails. Success emits load; failure emits error. Use the button to switch URLs:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiImage, HuiSpace } from '@nscode/handy-ui'
const list = ['/images/1.jpg', '/images/2.jpg', '/broken.png']
const index = ref(0)
const status = ref('Loading')
const next = () => {
index.value = (index.value + 1) % list.length
status.value = 'Loading'
}
</script>
<template>
<HuiSpace wrap align="center">
<HuiImage
:src="list[index]"
fit="cover"
:width="200"
:height="120"
@load="status = 'load emitted'"
@error="status = 'error emitted'"
/>
<HuiButton @click="next">Next image</HuiButton>
</HuiSpace>
<p style="margin-top: 12px">Current URL: {{ list[index] }} · {{ status }}</p>
</template>
Lazy loading
With lazy, loading starts when the image approaches the viewport (50px in advance). Until then, the loading placeholder is shown. Environments without IntersectionObserver load immediately. Scroll inside the box to load images in sequence:
<script setup lang="ts">
import { HuiImage, HuiSpace } from '@nscode/handy-ui'
// Append an index to each URL to make separate requests and show when scrolling triggers loading
const images = Array.from({ length: 12 }, (_, i) => `/images/${(i % 3) + 1}.jpg?n=${i + 1}`)
</script>
<template>
<div style="height: 320px; overflow-y: auto">
<HuiSpace wrap>
<HuiImage
v-for="src in images"
:key="src"
:src="src"
fit="cover"
:width="300"
:height="120"
lazy
/>
</HuiSpace>
</div>
</template>
Image previews
Provide preview-src-list to open a preview by clicking the image, or by focusing it with Tab and pressing Enter or Space. The preview starts at the position of src in the list unless initial-index specifies another index.
In the viewer you can:
- Click the arrows or press ← and → to switch images, wrapping around at either end.
- Use the toolbar to zoom out/in, rotate left/right, or reset. Press ↑ and ↓ to zoom in and out.
- Drag the enlarged image to pan.
- Close using the top-right button, clicking outside the image, or pressing Esc.
The large image uses alt as its alternative text when the list has one image; with several images it reads “Image n of m”.
<script setup lang="ts">
import { HuiImage, HuiSpace } from '@nscode/handy-ui'
const list = ['/images/1.jpg', '/images/2.jpg', '/images/3.jpg']
</script>
<template>
<HuiSpace wrap>
<HuiImage
v-for="(src, index) in list"
:key="src"
:src="src"
:width="100"
:height="75"
:preview-src-list="list"
:initial-index="index"
/>
</HuiSpace>
</template>
Without initial-index, the viewer starts at the position of src in the list, or the first image if src is absent. The first example below opens at 3.jpg. The second image's src is not in the list, so it opens at 1.jpg:
<script setup lang="ts">
import { HuiImage, HuiSpace } from '@nscode/handy-ui'
const list = ['/images/1.jpg', '/images/2.jpg', '/images/3.jpg']
</script>
<template>
<HuiSpace wrap>
<HuiImage src="/images/3.jpg" fit="cover" :width="120" :height="80" :preview-src-list="list" />
<HuiImage
src="/images/cat.jpg"
fit="cover"
:width="120"
:height="80"
:preview-src-list="list"
/>
</HuiSpace>
</template>
Standalone viewer
HuiImageViewer opens on mount and emits close after the leave transition completes. Use v-if to unmount it in response.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiImageViewer } from '@nscode/handy-ui'
const show = ref(false)
const list = ['/images/1.jpg', '/images/2.jpg']
</script>
<template>
<HuiButton @click="show = true">View large image</HuiButton>
<HuiImageViewer v-if="show" :url-list="list" hide-on-click-modal @close="show = false" />
</template>
infinite is enabled by default and wraps from the last image to the first. Disable it to stop at either end, where the corresponding arrow becomes unavailable. initial-index sets the opening image and switch reports subsequent changes. hide-on-click-modal defaults to false, so clicking outside the image does not close this standalone viewer:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiImageViewer } from '@nscode/handy-ui'
const list = ['/images/1.jpg', '/images/2.jpg', '/images/3.jpg']
const show = ref(false)
const current = ref<number>()
const open = () => {
current.value = undefined
show.value = true
}
</script>
<template>
<HuiButton @click="open">Open at image 2 without looping</HuiButton>
<p style="margin-top: 12px">
{{
current === undefined
? 'No image switch yet'
: `switch emitted: now viewing image ${current + 1}`
}}
</p>
<HuiImageViewer
v-if="show"
:url-list="list"
:initial-index="1"
:infinite="false"
@switch="current = $event"
@close="show = false"
/>
</template>
Placeholder and error slots
Custom slots take precedence over the corresponding image URL props. This example uses an invalid URL to demonstrate error content.
<script setup lang="ts">
import { HuiImage } from '@nscode/handy-ui'
</script>
<template>
<HuiImage src="data:image/png;base64,broken" :width="200" :height="100"
><template #placeholder>Loading image…</template
><template #error>Unable to display the image. Check its URL.</template></HuiImage
>
</template>
Viewer Semantic Attributes and Native Events
The visible fullscreen root of HuiImageViewer is also its role="dialog" node. It receives class, style, id, aria-*, tabindex, and native DOM listeners. Attributes can be updated or removed dynamically. An explicit aria-label="" keeps an empty name; removing the attribute restores the localized name.
The example uses offline images. The next-image button retains its own behavior; its click also reaches the native root listener once. event.currentTarget is the dialog, while event.target remains the actual clicked descendant.
<script setup lang="ts">
import { ref, useId } from 'vue'
import { HuiButton, HuiImageViewer, HuiSpace } from '@nscode/handy-ui'
const show = ref(false)
const active = ref(0)
const clicks = ref(0)
const target = ref('No click')
const previewId = useId()
const helpId = useId()
const images = [1, 2].map(
(index) =>
'data:image/svg+xml;charset=utf-8,' +
encodeURIComponent(
`<svg xmlns="http://www.w3.org/2000/svg" width="400" height="240"><rect width="400" height="240" fill="${index === 1 ? '#409eff' : '#67c23a'}"/><text x="200" y="135" text-anchor="middle" fill="white" font-size="64">${index}</text></svg>`
)
)
const open = () => {
active.value = 0
show.value = true
}
const onPreviewClick = (event: MouseEvent) => {
clicks.value++
target.value = (event.currentTarget as HTMLElement).getAttribute('role') ?? ''
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="open">Open described preview</HuiButton>
<p :id="helpId">
Arrow keys or buttons switch images. The preview name follows the image number.
</p>
<p>Native clicks: {{ clicks }}; listener target: {{ target }}</p>
<HuiImageViewer
v-if="show"
:id="previewId"
class="preview-appearance"
style="outline: 2px solid var(--hui-color-primary); outline-offset: -2px"
:url-list="images"
:aria-label="'Attachment preview ' + (active + 1) + ' / ' + images.length"
:aria-describedby="helpId"
data-gallery="attachments"
@click="onPreviewClick"
@switch="active = $event"
@close="show = false"
/>
</HuiSpace>
</template>
HuiImage Props
| Prop | Type | Default | Description |
|---|---|---|---|
| src | string | - | Image URL; required |
| alt | string | '' | Alternative text; also used for the large image when the preview has only one image |
| fit | 'fill' | 'contain' | 'cover' | 'none' | 'scale-down' | 'fill' | Image fit behavior, matching CSS object-fit |
| lazy | boolean | false | Load lazily when approaching the viewport (50px in advance) |
| previewSrcList | string[] | - | Preview image list; a nonempty list enables click-to-preview |
| initialIndex | number | - | Opening preview index (zero-based and clamped to the valid range); defaults to the position of src |
| zIndex | number | - | Preview stacking order; follows ConfigProvider when omitted, defaulting to 2000 |
| width | string | number | - | Width; numbers are pixels and strings are used as provided |
| height | string | number | - | Height; numbers are pixels and strings are used as provided |
| round | boolean | false | Apply border-radius: 50% |
| placeholder | string | - | Loading placeholder image URL; defaults to a spinner |
| error | string | - | Error image URL; defaults to localized error text |
HuiImage Events
| Event | Parameters | Description |
|---|---|---|
| load | (event: Event) | Emitted when the image loads |
| error | (event: Event) | Emitted when the image fails to load |
HuiImage Slots
| Slot | Scope | Description |
|---|---|---|
| placeholder | - | Loading content, taking precedence over the placeholder image prop |
| error | - | Error content, taking precedence over the error image prop |
HuiImageViewer Props
| Prop | Type | Default | Description |
|---|---|---|---|
| urlList | string[] | [] | Images to preview |
| initialIndex | number | 0 | Opening image index |
| zIndex | number | - | Preview stacking order; follows ConfigProvider when omitted, defaulting to 2000 |
| infinite | boolean | true | Wrap from the first image to the last and vice versa |
| hideOnClickModal | boolean | false | Close when clicking outside the image (always enabled inside HuiImage) |
| alt | string | - | Alternative text for the large image, used only when urlList has one image; with several images, or when omitted, it reads “Image n of m” |
HuiImageViewer Events
| Event | Parameters | Description |
|---|---|---|
| close | - | Emitted after closing and completing the leave transition; the viewer can then be unmounted with v-if |
| switch | (index: number) | Emitted after switching images, with the new index |
Types
import type { ImageProps, ImageViewerProps, ImageViewerEmits } from '@nscode/handy-ui'
interface ImageProps {
src: string
alt?: string
fit?: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down'
lazy?: boolean
previewSrcList?: string[]
initialIndex?: number
zIndex?: number
width?: string | number
height?: string | number
round?: boolean
placeholder?: string
error?: string
}
interface ImageViewerProps {
urlList: string[]
initialIndex?: number
zIndex?: number
infinite?: boolean
hideOnClickModal?: boolean
alt?: string
}
interface ImageViewerEmits {
close: []
switch: [index: number]
}