在使用VUE开发时,可能会遇到这么一个需求,第一个界面会出现小图片,用户可以点击小图片进入查看放大的图片。这种需求最容易出现在公众号上,毕竟手机屏幕太小,在展现文字及图片时,图片显示的空间就有限了,这个时候如果你可以点击这个图片,图片能放大到全屏,是否就可以满足这个需求了呢?那以下就是使用VUE完成这个功能,以下代码可做参考
父组件:
子组件
源码如下:
父组件:
<template> <div > //imgBaseUrl为图片URL <img v-if="imgBaseUrl" style="width:100%" :src="imgBaseUrl" @click.self="showBigImage(imgBaseUrl)"> //显示放大图片的组件 <ShowPhoto :visible="photoVisible" :url="bigImgUrl" @closeClick="()=>{photoVisible=false}"></ShowPhoto> </div> </template> export default { data() { return { photoVisible: false } }, methods: { showBigImage(imgUrl) {//点击图片函数,点击后,把photoVisible设置成true if (imgUrl != "") { this.photoVisible = true; this.cacheInfo() } } }
子组件
<template> <div v-show="visible" @click="closeClick" class="showPhoto"> <img class="img" :src="url" alt="图片加载失败"> </div> </template> <script> import {MessageBox} from 'mint-ui' export default { props:{ url: { type: String, default: '' }, visible : { type: Boolean, default: false }, }, methods:{ closeClick(){//子组件可以使用 $emit 触发父组件的自定义事件 this.$emit('closeClick') } } } </script> <style lang="stylus" scoped> .showPhoto position:fixed top:0 left:0 width: 100% height: 100% background: rgba(0,0,0,0.5) z-index: 999 display: flex .img display: block margin: auto 0 width 100% text-align: center; </style>