需求:我们在开发中经常会遇到通过点击某个按钮或者文字实现图片的预览功能。这里我们分别介绍vue2和vue3里面如何实现图片预览方法
1,通过ref给el-image组件上面获取DOM元素,然后我们通过clickHandler方法来实现点击图片预览
<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>
2,这里我们区别vue2的使用,我们通过v-if判断是否预览弹窗图片的。
<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>