v-viewer:Vue图片预览插件

2,993 阅读1分钟

一、安装

npm install v-viewer@3 //指定版本以免发生报错

二、全局注册

import { createApp } from 'vue'
import App from './App.vue'
import 'viewerjs/dist/viewer.css'
import VueViewer from 'v-viewer'

const app = createApp(App)

let options = {
  defaultOptions: {
    zIndex: 99999,
    title: false,
    toolbar: false,
  },
}

app.use(VueViewer, options)

三、局部注册

import 'viewerjs/dist/viewer.css'
import { component as Viewer } from "v-viewer"

export default {
  components: { Viewer },
}

四、相关配置

// 默认配置
defaultOptions: {
    zIndex: 3000,
    inline: false, // 启用内联模式
    button: true, // 在查看器右上角显示按钮
    navbar: true, // 指定导航栏的可见性
    title: false, // 指定标题的可见性和内容
    toolbar: false, // 指定工具栏及其按钮的可见性和布局
    tooltip: true, // 放大或缩小时显示带有图像比率(百分比)的工具提示
    movable: true, // 启用以移动图像
    zoomable: true, // 启用以缩放图像
    rotatable: false, // 启用以旋转图像
    scalable: true, // 启用以缩放图像。
    transition: true, // 为某些特殊元素启用CSS3转换
    fullscreen: false, // 启用以在播放时请求全屏
    keyboard: true, // 启用键盘支持。
    url: 'src', // 定义获取原始图像URL以供查看的位置
}

五、使用插件

1、通过指令调用

<div v-viewer>
   <img v-for="src in images" :key="src" :src="src"/>
</div>

2、组件形式使用

<viewer :images="images">
  <img v-for="src in images" :key="src" :src="src">
</viewer>

3、通过API调用(推荐使用)

由于全局注册v-viewer,组件、指令和api会被一起安装到app全局,可直接获取并使用全局变量 $viewerApi

在Vue2中使用:

<a v-if="images?.length" @click="showImagesInViewer(images)">查看</a>
showImagesInViewer(urls) {
  urls instanceof Array &&
  urls?.length &&
  this.$viewerApi({ images: urls })
},

在Vue3 setup中使用:

const { proxy }: any = getCurrentInstance()
// 图片预览
const loadOverImg = (img: string) => {
  let images = [img]
  proxy.$viewerApi({
    images: images,
  })
}