v-viewer:vue3图片查看器
:一个方便易用的vue3 图片查看器
一、安装
1、npm/yarn 安装
npm install v-viewer@next or yarn add viewer@next
-
全局注册插件
引入v-viewer及必需的css样式,并使用app.use()注册插件 组件、指令和api会被一起安装到app全局
import {
createApp } from vue
import App from ./App.vue // 视自己项目而定
import viewerjs/dist/viewer.css
import VueViewer from v-viewer
const app = createApp(App)
app.use(VueViewer, {
defaultOptions: {
// 自定义默认配置
}
}
-
局部注册
import viewerjs/dist/viewer.css
import {
component as Viewer } from "v-viewer"
export default {
components: {
Viewer },
}
2、cdn引入:
<link href="//unpkg.com/viewerjs/dist/viewer.css" rel="stylesheet"> <script src="//unpkg.com/viewerjs/dist/viewer.js"></script> <script src="//unpkg.com/v-viewer@next/dist/index.umd.js"></script>
全局注册插件:
app.use(VueViewer.default, {
defaultOptions: {
// 自定义默认配置
}
}
二、main.js设置默认配置
示例:
defaultOptions: {
zIndex: 3000,
inline: false, // Default: false. Enable inline mode.
button: true, // Show the button on the top-right of the viewer.
navbar: true, // Specify the visibility of the navbar.
title: false, // Specify the visibility and the content of the title.
toolbar: false, // Specify the visibility and layout of the toolbar its buttons.
tooltip: true, // Show the tooltip with image ratio (percentage) when zooming in or zooming out.
movable: true, // Enable to move the image.
zoomable: true, // Enable to zoom the image.
rotatable: false, // Enable to rotate the image.
scalable: true, // Enable to scale the image.
transition: true, // Enable CSS3 Transition for some special elements.
fullscreen: false, // Enable to request full screen when play.
keyboard: true, // Enable keyboard support.
url: src, // Default: src. Define where to get the original image URL for viewing.
}
三、使用
通过指令调用:
<div v-viewer> <img v-for="src in images" :key="src" :src="src"/> </div>
组件形式使用:
<viewer :images="images"> <img v-for="src in images" :key="src" :src="src"> </viewer>
通过API调用:
<a v-if="images?.length" @click="showImagesInViewer(images)">查看</a>
showImagesInViewer(urls) {
urls instanceof Array &&
urls?.length &&
this.$viewerApi({
images: urls })
},
-
vue3 setup
由于全局注册v-viewer,组件、指令和api会被一起安装到app全局,可直接获取并使用全局变量 $viewerApi
import {
getCurrentInstance } from vue
const $viewerApi = getCurrentInstance().appContext.config.globalProperties.$viewerApi
$viewerApi({
images: [] })
或者,手动导入 api 使用 感谢 在评论区补充的方案
import {
api as viewerApi } from v-viewer
viewerApi({
images: [] })
