Image

Image

출처: 문서

본문

img의 네이티브 기능 외에도 지연 로드(lazy load), 커스텀 placeholder, 로드 실패 처리 등을 지원하는 이미지 컴포넌트예요.

기본 사용 (Basic Usage)

fit로 이미지가 컨테이너에 맞게 어떻게 리사이즈될지 지정해요. 네이티브 object-fit와 같아요.

<template>
  <div class="demo-image">
    <div v-for="fit in fits" :key="fit" class="block">
      <span class="demonstration">{{ fit }}</span>
      <el-image :style="{ width: '100px', height: '100px' }" :src="url" :fit="fit" />
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ImageProps } from 'element-plus'

const fits = [
  'fill',
  'contain',
  'cover',
  'none',
  'scale-down',
] as ImageProps['fit'][]
const url =
  'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
</script>
.demo-image .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 20%;
  min-width: 100px;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image .block:last-child {
  border-right: none;
}
.demo-image .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

Placeholder

이미지가 아직 로드되지 않았을 때 커스텀 placeholder 내용을 placeholder 슬롯으로 지정할 수 있어요.

.demo-image__placeholder .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 49%;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image__placeholder .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.demo-image__placeholder .el-image {
  padding: 0 5px;
  max-width: 300px;
  max-height: 200px;
}

.demo-image__placeholder.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
.demo-image__placeholder .dot {
  animation: dot 2s infinite steps(3, start);
  overflow: hidden;
}

로드 실패 (Load Failed)

이미지 로드 중 오류가 발생했을 때 커스텀 실패 내용을 error 슬롯과 viewer-error 슬롯으로 지정할 수 있어요.

<template>
  <div class="demo-image__error">
    <el-image
      :src="url"
      fit="contain"
      :preview-src-list="srcList"
      preview-teleported
    >
      <template #error>
        <div class="image-slot">
          <el-icon><icon-picture /></el-icon>
          <span>error</span>
        </div>
      </template>
    </el-image>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Picture as IconPicture } from '@element-plus/icons-vue'

const showPreview = ref(false)

const srcList = [
  'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
  'https://errorSrc',
]
const url =
  'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
</script>
.demo-image__error .el-image {
  max-width: 300px;
  max-height: 200px;
  width: 100%;
}

.demo-image__error .image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  font-size: 30px;
  height: 200px;
  background: #fff;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.image-viewer-slot {
  background: var(--el-fill-color-light);
}
.viewer-error {
  color: #000;
}

지연 로드 (Lazy Load)

TIP

네이티브 lazy loading은 2.2.3부터 지원돼요. loading = "lazy"를 사용해 lazy = true를 대체할 수 있어요. 현재 브라우저가 네이티브 lazy loading을 지원하면 네이티브 lazy loading을 먼저 사용하고, 그렇지 않으면 스크롤을 통해 구현돼요.

lazy = true로 지연 로드를 사용해요. 설정하면 이미지가 뷰에 스크롤될 때까지 로드하지 않아요. 스크롤 리스너를 추가할 스크롤 컨테이너는 scroll-container로 지정할 수 있어요. 지정하지 않으면 overflow 속성이 auto 또는 scroll인 가장 가까운 부모 컨테이너가 돼요.

이미지 미리보기 (Image Preview)

previewSrcList prop을 설정하면 큰 이미지 미리보기를 허용할 수 있어요. 처음 미리보기할 첫 번째 이미지의 위치는 initial-index로 초기화할 수 있고 기본 초기 위치는 0이에요.

수동으로 미리보기 열기 (Manually Open Preview) 2.9.4

show-preview를 직접 제어하면서 imageRef의 showPreview() 메서드로 수동으로 미리보기를 열 수 있어요.

<template>
  <div class="demo-image__preview">
    <el-image ref="imageRef" :src="url" :preview-src-list="srcList" preview-teleported />
    <el-button type="primary" @click="handleClick">preview controlled</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

import type { ImageInstance } from 'element-plus'

const url =
  'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
const srcList = [
  'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
  'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
  'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
  'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
  'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
  'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
  'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg',
]

const imageRef = ref()
const showPreview = ref(false)

const handleClick = () => {
  imageRef.value!.showPreview()
}
</script>

커스텀 툴바 (Custom Toolbar) 2.9.4

toolbar 슬롯으로 툴바 내용을 커스터마이즈할 수 있어요. 2.9.7부터 이 슬롯에는 setActiveItem 함수가 추가되어 index에 따라 전환할 수 있어요.

<template>
  <div class="demo-image__preview">
    <el-image :src="url" :preview-src-list="srcList" preview-teleported>
      <template #toolbar>
        <div class="image-viewer__toolbar">
          <el-icon @click="download(activeIndex)"><Download /></el-icon>
        </div>
      </template>
    </el-image>
  </div>
</template>

<script setup lang="ts">
import { ElIcon } from 'element-plus'
import {
  Back,
  DArrowRight,
  Download,
  Refresh,
  RefreshLeft,
  RefreshRight,
  Right,
  ZoomIn,
  ZoomOut,
} from '@element-plus/icons-vue'

const url =
  'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
const srcList = [
  'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
  'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
  'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
  'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
  'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
  'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
  'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg',
]

const download = (index: number) => {
  const url = srcList[index]
  const suffix = url.slice(url.lastIndexOf('.'))
  const filename = Date.now() + suffix

  fetch(url)
    .then((response) => response.blob())
    .then((blob) => {
      const blobUrl = URL.createObjectURL(new Blob([blob]))
      const link = document.createElement('a')
      link.href = blobUrl
      link.download = filename
      document.body.appendChild(link)
      link.click()
      URL.revokeObjectURL(blobUrl)
      link.remove()
    })
}
</script>

커스텀 진행률 (Custom progress) 2.9.4

show-progress prop을 설정해 이미지를 미리보기할 때 진행률을 표시할지 제어할 수 있어요. 2.9.8 이후부터는 progress 슬롯을 사용하면 진행률 내용이 표시돼요.

Image API

Image Attributes

Name Description Type Default
src image source, same as native. string ''
fit indicate how the image should be resized to fit its container, same as object-fit. enum ''
hide-on-click-modal when enabling preview, use this flag to control whether clicking on backdrop can exit preview mode. boolean false
loading 2.2.3 Indicates how the browser should load the image, same as native. enum —
lazy whether to use lazy load. boolean false
scroll-container the container to add scroll listener when using lazy load. By default, the container to add scroll listener when using lazy load. string / object —
alt native attribute alt. string —
referrerpolicy native attribute referrerPolicy. string —
crossorigin native attribute crossorigin. enum —
preview-src-list allow big image preview. array []
z-index set image preview z-index. number —
initial-index initial preview image index, less than the length of url-list. number 0
close-on-press-escape whether the image-viewer can be closed by pressing ESC. boolean true
preview-teleported whether to append image-viewer to body. A nested parent element attribute transform should have this attribute set to true. boolean false
infinite whether the viewer preview is infinite. boolean true
zoom-rate the zoom rate of the image viewer zoom event. number 1.2
scale 2.11.3 the preview image scale. number 1
min-scale 2.4.0 the min scale of the image viewer zoom event. number 0.2
max-scale 2.4.0 the max scale of the image viewer zoom event. number 7
show-progress 2.9.4 whether to display the preview image progress content. boolean false

Image Events

Name Description Type
load same as native load. Function
error same as native error. Function
switch trigger when switching images. Function
close trigger when clicking on close button or when hide-on-click-modal enabled clicking on backdrop. Function
show trigger when the viewer displays Function

Image Slots

Name Description Type
placeholder custom placeholder content when image hasn't loaded yet. -
error custom image load failed content. -
image viewer slots when you allow big image preview, image viewer slots all can be used. -

Image Exposes

Name Description Type
showPreview 2.9.4 manually open preview big image Function

Image Viewer API

Image Viewer Attributes

Name Description Type Default
url-list preview link list. array []
z-index preview backdrop z-index. number / string —
initial-index the initial preview image index, less than or equal to the length of url-list. number 0
infinite whether preview is infinite. boolean true
hide-on-click-modal whether user can emit close event when clicking backdrop. boolean false
teleported whether to append image itself to body. A nested parent element attribute transform should have this attribute set to true. boolean false
zoom-rate 2.2.27 the zoom rate of the image viewer zoom event. number 1.2
scale 2.11.3 the preview image scale. number 1
min-scale 2.4.0 the min scale of the image viewer zoom event. number 0.2
max-scale 2.4.0 the max scale of the image viewer zoom event. number 7
close-on-press-escape whether the image-viewer can be closed by pressing ESC. boolean true
show-progress 2.9.4 whether to display the preview image progress content boolean false

Image Viewer Events

Name Description Type
close trigger when clicking on close button or when hide-on-click-modal enabled clicking on backdrop. Function
error 2.11.3 same as native error. Function
switch trigger when switching images. Function
rotate 2.3.13 trigger when rotating images. Function

Image Viewer Slots

Name Description Type
viewer custom content -
progress 2.9.4 custom progress content (Priority is higher than show-progress prop) object
toolbar 2.9.4 custom toolbar content object
viewer-error 2.11.3 custom image load failed content. object

Image Viewer Exposes

Name Description Type
setActiveItem manually switch image Function

Type Declarations

type ImageViewerAction = 'zoomIn' | 'zoomOut' | 'clockwise' | 'anticlockwise'
type ImageViewerActionOptions = {
  enableTransition?: boolean
  zoomRate?: number
  rotateDeg?: number
}

더 알아보기 (Learn more)