Requirements: In development, we often encounter the preview function of images by clicking a button or text. Here we introduce how to implement the image preview method in vue2 and vue3 respectively.
Vue2 implements image preview through el-image components
1. Get the DOM element through ref to the el-image component, and then we use the clickHandler method to achieve click image preview
<template>
<div>
<el-button type="primary" @click=PreviewImg() >图片</el-button>
<el-image
ref="elImage"
style="width: 0; height: 0;"
:src="bigImageUrl"
:preview-src-list="logicImageList">
</el-image>
</div>
</template>
<script>
export default {
data () {
return {
bigImageUrl: '',
logicImageList: []
}
},
methods :{
PreviewImg() {
// 调用接口之后获取图片数据
this.logicImageList = res.data.map((item) => {
return item.accessUrl })
this.$nextTick(() => {
this.$refs.elImage.clickHandler()
})
}
}
}
</script>
Vue3 implements image preview through the el-image-viewer component
2. Here we distinguish the use of vue2. We use v-if to determine whether to preview the pop-up image.
<template>
<div>
<el-button type="primary" @click=PreviewImg() >图片</el-button>
<el-image-viewer
style="width: 100px; height: 100px"
v-if="state.imgViewerVisible"
@close="closeImgViewer"
:url-list="state.srcList">
</el-image-viewer>
</div>
</template>
<script setup lang="ts" name="uploadFile">
import {
nextTick, reactive } from 'vue';
const state: any = reactive({
imgViewerVisible: false,
srcList: []
})
function PreviewImg() {
// 调用接口之后获取图片数据
state.srcList= res.data.map((item) => {
return item.accessUrl })
state.imgViewerVisible = true
}
function closeImgViewer () {
state.imgViewerVisible = false
}
}
</script>