vue3中用v-viewer封装一个图片预览组件

799 阅读1分钟

安装v-viewer

npm install v-viewer@next viewerjs

组件内容

<script setup lang="ts">
import { ref } from "vue";
import "viewerjs/dist/viewer.css";
import { api as viewerApi } from "v-viewer";

defineOptions({
  name: "ImageGallery"
});

const props = defineProps({
  // 传入图片列表,支持两种格式
  // 1. 图片对象列表 [{src: ''}],会默认从 src取,可以调整取参的key
  // 2. 图片URL列表['url1', 'url2']
  imageList: {
    type: Array,
    default: () => []
  },
  //  图片对象列表,会默认从 src取,可以调整取参的key
  imageUrlKey: {
    type: String,
    default: () => "src"
  }
});

const $viewer = ref(null);

// 预览图片,默认从第一个开始预览,调方法的时候,可以修改
const previewImage = (initialIndex = 0) => {
  const imageList = props.imageList;

  if (!imageList || imageList.length === 0) {
    console.error("请传入正确的图片数组");
    return;
  }
  const previewConfig = {
    options: {
      toolbar: true,
      initialViewIndex: initialIndex
    },
    images: imageList
  };
  if (imageList[0][props.imageUrlKey]) {
    previewConfig.options.url = props.imageUrlKey;
  }

  // If you use the `app.use` full installation, you can use `this.$viewerApi` directly
  $viewer.value = viewerApi(previewConfig);
};

defineExpose({
  previewImage
});
</script>
<template>
  <div />
</template>
<style lang="scss" scoped></style>

引用组件

<script setup lang="ts">
import { ref } from "vue";
import ImageGallery from "@/components/ImageGallery/index.vue";

const imageGalleryRef = ref(null);
// 省略其他代码


function openImageGallery(idx) {
  imageGalleryRef.value && imageGalleryRef.value.previewImage(idx);
}

</script>

<template>
    <div>
        // 省略其他代码
        
        <ImageGallery
            :image-list="dataList"
            imageUrlKey="fileUrl"
            ref="imageGalleryRef"
        />

        <span class="btn-preview" @click="openImageGallery(2)">
          预览
        </span>
        
    </div>
    
</template>

言简意赅~ 希望对你有帮助~