创建一个图片预览组件

vue
<script setup lang="ts">
import { ref, watchEffect } from "vue";

const props = defineProps<{
  imageList?: string[];
}>();

const visible = ref(false);
const list = ref<string[]>([]);
const currentIndex = ref<number>(0);

watchEffect(() => {
  const { imageList } = props;
  if (!imageList?.length) return;
  list.value = [...imageList];
});

function open(data: { previewIndex: number }) {
  const { previewIndex } = data;
  currentIndex.value = previewIndex;
  visible.value = true;
}

const emit = defineEmits<{
  (e: "close"): void;
}>();

function close() {
  visible.value = false;
  emit("close");
}

// 切换图片时触发
function onSwitch(index: number) {
  currentIndex.value = index;
}

defineExpose({
  open,
  close,
});
</script>

<template>
  <div id="image-preview" v-if="visible">
    <el-image-viewer
      :url-list="list"
      @close="close"
      @switch="onSwitch"
      :initial-index="currentIndex"
      show-progress
    >
    </el-image-viewer>
  </div>
</template>

<style scoped lang="scss">
#image-preview {
  position: relative;

  :deep(.el-image-viewer__progress) {
    position: absolute;
    top: 0;
    height: 40px;
    width: 100%;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 0;
    font-weight: 400;
  }
}
</style>
评论 隐私政策