图片预览

借助element的图片预览组件

功能

  1. 当点击点击遮罩层时, 关闭 preview hide-on-click-modal
  2. 预览图片时, 关闭页面的鼠标滚轮 stopScroll
  3. 可以在图片预览处切换查看的图片 imageList

基础封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<script setup>
import { ref } from 'vue'

const props = defineProps({
imageList: {
type: Array,
},
})
//开始预览的
const previewImageIndex = ref(null)

//关闭图片预览
const closeImgViewer = () => {
startScroll()
previewImageIndex.value = null
}

const show = (index) => {
stopScroll()
previewImageIndex.value = index
}

//禁止滚动
const stopScroll = () => {
document.body.style.overflow = "hidden"
}
//开始滚动
const startScroll = () => {
document.body.style.overflow = "auto"
}

defineExpose({show})
</script>

<template>
<div class="image-view">
<el-image-viewer
:initial-index="previewImageIndex"
hide-on-click-modal
:url-list="imageList"
@close="closeImgViewer"
v-if="previewImageIndex != null"
>

</el-image-viewer>
</div>
</template>

<style scoped>
.image-view {
el-image-viewer__mask {
/* 背景透明度 */
opacity: 0.9;
}
}
</style>

调用

1
2
3
4
5
6
<!-- 图片预览 -->
<ImageViewer
ref="imageViewerRef"
:imageList="previewImageList"
>
</ImageViewer>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//图片预览
const imageViewerRef = ref(null)
const previewImageList = ref([])
const imagePreview = () => {
nextTick(() => {
//等待下一次 DOM 更新循环结束后执行回调函数中的代码
const imageNodeList = document
.querySelector('#detail')
.querySelectorAll("img")

const imageList = []
imageNodeList.forEach((item, index) => {
const src = item.getAttribute("src")
imageList.push(src)
item.addEventListener("click", () => {
imageViewerRef.value.show(index)
})
})
previewImageList.value = imageList
})
}