<template>
  <!-- 挂载viewer到元素上，设置一个id，因为需求不需要展示图片，点击按钮时直接查看图片即可，所以v-show="false"-->
  <div v-if="visible">
    <div id="viewerjs" v-show="false">
      <img :src="item" v-for="(item, index) in imgarr" :key="index" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';

const props = defineProps({
  url: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  },
  urlList: Array,
  currentIndex: {
    type: Number,
    default: 0
  }
});

const emits = defineEmits(['close']);
const imgarr = ref([]);

onMounted(() => {
  if (props.url) {
    imgarr.value.push(props.url);
  } else if (props.urlList) {
    imgarr.value = props.urlList;
  }

  if (imgarr.value.length > 0) {
    lookimg();
  }
});
const lookimg = () => {
  //更改了图片数组imgarr，并且图片列表使用v-for渲染，需要使用this.$nextTick获取更新后的dom
  nextTick(() => {
    const viewerdom = document.getElementById('viewerjs');
    const viewer = new Viewer(viewerdom, {
      title: false,
      navbar: true,
      hide: () => {
        //销毁视图
        viewer.destroy();
        emits('close', false);
      }
    });
    viewer.view(props.currentIndex);
    viewer.show();
  });
};
</script>
<style lang="less">
//目录图片预览时加载动画的时间
.viewer-transition {
  transition: all 0.1s !important;
}
</style>
