父组件打开图片可以引入下面组件
<template>
<div class="image-viewer" style="position: absolute; z-index: 9999999">
<div class="image-container">
<img
:src="imageUrl"
style=""
alt="Image"
@click="closeViewer"
:style="imageStyle" //主要代码
/>
</div>
</div>
</template>
<script>
export default {
props: {
imageUrl: String
},
data() {
return {
containerWidth: 0, //主要代码
containerHeight: 0 //主要代码
};
},
computed: {
//主要代码
imageStyle() {
return {
maxWidth: `${this.containerWidth}px`,
maxHeight: `${this.containerHeight}px`,
width: "auto",
height: "auto"
};
}
},
mounted() {
//主要代码
this.updateContainerSize();
window.addEventListener("resize", this.updateContainerSize);
},
beforeDestroy() {
//主要代码
window.removeEventListener("resize", this.updateContainerSize);
},
methods: {
//主要代码
updateContainerSize() {
this.containerWidth = window.innerWidth * 0.8; // Adjust as needed
this.containerHeight = window.innerHeight * 0.8; // Adjust as needed
},
closeViewer() {
this.$emit("close");
}
}
};
</script>
<style scoped>
/*主要代码*/
.image-viewer {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
overflow-y: auto;
background: rgba(0, 0, 0, 0.4);
}
或者
.image-viewer {
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
.image-container {
position: relative;
z-index: 9999;
overflow-y: auto;
display: inline-block;
}
/*主要代码*/
img {
position: static;
object-fit: cover;
display: block;
max-width: 100%;
max-height: 100%;
z-index: 9999999;
}
</style>