vue2使用v-viewer实现图片预览

v-viewer
用于图片浏览的Vue组件,支持旋转、缩放、翻转等操作,基于viewer.js。

中文文档:Vue图片浏览组件v-viewer,支持旋转、缩放、翻转等操作 | Mirari’s Blog

代码示例:https://mirari.cc/v-viewer/

在Vue.js 2中使用v-viewer插件实现图片预览功能相对简单。v-viewer是一个Vue.js的图片预览插件,可以轻松实现图片的放大、缩小和滑动预览等功能。以下是实现步骤:

安装 v-viewer 插件:
在项目目录下使用 npm 或 yarn 安装 v-viewer 插件。

npm install v-viewer --save  
npm i -S viewerjs
# 或
yarn add v-viewer
yarn add  viewerjs

在 main.js 文件中引入和配置 v-viewer 插件:

这行放在:import App from './App.vue'; 之前
import Viewer from 'v-viewer';
 
import 'viewerjs/dist/viewer.css';
 
Vue.use(Viewer);
或者
Vue.use(Viewer, {
  defaultOptions: {
    zIndex: 9999, // 设置图片预览组件的层级,确保能在其他组件之上
  },
});

在这里插入图片描述

在需要预览图片的组件中使用 v-viewer 指令:

<template>
  <div>
    <!-- 点击图片触发预览 -->
    <img v-for="(image, index) in imageList" :key="index" :src="image" v-viewer />
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageList: [
        'https://example.com/image1.jpg',
        'https://example.com/image2.jpg',
        // 添加更多图片链接
      ],
    };
  },
};
</script

也可以使用以下方法

<template>
  <div>
    <button type="button" class="button" @click="previewURL">URL Array</button>
  </div>
</template>
<script>
  export default {
    data() {
      sourceImageURLs: [
        'https://picsum.photos/200/200?random=1',
        'https://picsum.photos/200/200?random=2',
      ],
    },
    methods: {
      previewURL () {
        // 如果使用`app.use`进行全局安装, 你就可以像这样直接调用`this.$viewerApi`
        const $viewer = this.$viewerApi({
          images: this.sourceImageURLs
        });
      },
    },
  };
</script>

在上面的代码中,我们将 v-viewer 指令应用在 img 标签上,这样点击图片时会触发预览效果。

猜你喜欢

转载自blog.csdn.net/weixin_43784341/article/details/132062172