Element Plus图片预览的最佳使用方式

1,047 阅读1分钟

前言

  • 根据element plus文档,图片想要使用大图预览,必须通过el-image标签
  • 但有时候页面不一定需要展示图片,可能有时候只是一个查看按钮,或者图片标题,点击时才显示大图预览
  • 项目内部可能需要封装一个preview方法,传入一个文件url,当文件是图片时,用大图预览,其他类型文件时,使用文件在线预览服务
  • 基于以上问题,我们需要一个通过函数式,使用大图预览的API

效果

previewImg.gif

使用

安装

@planckdev/element-plus 文档地址:www.npmjs.com/package/@pl…

pnpm install @planckdev/element-plus

调用

import { preview } from '@planckdev/element-plus/utils'

const previewImage = async () => {
  await preview('https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg')
  console.log('Preview Closed')
}

源码

import { ElImageViewer } from 'element-plus'
import { createApp, defineComponent, h } from 'vue'

export function preview(url: string, imgList: string[] = []) {
  return new Promise<void>((resolve) => {
    const urlList = [...imgList]
    let initialIndex = urlList.indexOf(url)
    if (initialIndex === -1) {
      urlList.unshift(url)
      initialIndex = 0
    }

    const container = document.createElement('div')

    const app = createApp(defineComponent({
      setup() {
        return () => [
          h('style', 'body { overflow: hidden !important;  }'), // 解决弹窗时,页面有滚动条的问题
          h(ElImageViewer, {
            initialIndex,
            urlList,
            onClose() {
              destroyViewer()
              resolve()
            },
          })]
      },
    }))
    app.mount(container)
    document.body.appendChild(container)

    function destroyViewer() {
      app.unmount()
      document.body.removeChild(container)
    }
  })
}