vue中实现图片预览功能

实现思路

结合表单元素的file类型,再使用定位将img标签展示图片覆盖到表单上面,将表单透明度设置为0并设置定位,定位层级比img更高。
再通过chang事件监听文件是否发生改变,并使用URL.createObjectURL将图片转换为临时路径,并赋值给展示图片

代码

      <div class="upload-pic">
        <div class="upload-title">{{uploadTitle}}div>
        <div class="upload-box">
          <input type="file" id="file" class="file-path" @change="changepic" :accept="accept" />
          <img class="show-img" :src="imgSrc" alt />
        div>
      div>
    //图片预览功能
   changepic(e) {
     let file = e.target.files[0];
     let url = URL.createObjectURL(file);
     this.imgSrc = url;
   }
   .upload-pic {
     margin-top: $titleMarginTop;

     .upload-title {
       font-size: $titleFontSize;
       font-weight: bold;
     }
     .upload-box {
       position: relative;
       @include uploadPic;
       margin-top: 14px;
       .file-path {
         position: absolute;
         @include uploadPic;
         outline: none;
         opacity: 0;
         z-index: 10;
       }
       .show-img {
         position: absolute;
         @include uploadPic;
         left: 0;
         vertical-align: middle;
         border-radius: $radiusSize * 2;
       }
     }
   }
   @mixin uploadPic {
     width: 80px;
	 height: 80px;
   }

你可能感兴趣的:(功能)