溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue圖片上傳本地預(yù)覽組件使用詳解

發(fā)布時間:2020-10-21 04:08:07 來源:腳本之家 閱讀:123 作者:codingNoob 欄目:web開發(fā)

最近項目一直在使用vue,以前只是用vue做過一些簡單的demo對數(shù)據(jù)進行增刪改,并沒有用于實際開發(fā)項目。今天就想了解一下如何用vue實現(xiàn)常見的圖片上傳前本地預(yù)覽效果。

效果預(yù)覽:

vue圖片上傳本地預(yù)覽組件使用詳解

<template>
 <div class="image-view">
 <div class="addbox">
  <input type="file" @change="getImgBase()">
  <div class="addbtn">+</div>
 </div>
 <div class="view">
  <div class="item" v-for="(item, index) in imgBase64">
  <span class="cancel-btn" @click="delImg(index)">x</span>
  <img :src="item">
  </div>
 </div>
 </div>
</template>
<script>
 export default {
 name: 'imageView',
 data (){
  return {
  imgBase64:[] //存儲img base64的值將值傳給后端處理
  }
 },
 methods: {
  //獲取圖片base64實現(xiàn)預(yù)覽
  getImgBase(){
  var _this = this;
  var event = event || window.event;
  var file = event.target.files[0];
  var reader = new FileReader(); 
  //轉(zhuǎn)base64
  reader.onload = function(e) {
   _this.imgBase64.push(e.target.result);
  }
  reader.readAsDataURL(file);
  },
  //刪除圖片
  delImg(index){
  this.imgBase64.splice(index,1);
  }
 }
 }
</script>
<style scoped>
 *{margin:0 auto;padding:0;font-family:"微軟雅黑";}
 .clearboth::after{
 content:"";
 display:block;
 clear:both;
 }
 .image-view{
 width:400px;
 height:300px;
 margin:50px auto;
 }
 .image-view .addbox{
 float:left;
 position:relative;
 height:100px;
 width:100px;
 margin-bottom:20px;
 text-align:center;
 }
 .image-view .addbox input{
 position:absolute;
 left:0;
 height:100px;
 width:100px;
 opacity:0;
 }
 .image-view .addbox .addbtn{
 float:left;
 height:100px;
 width:100px;
 line-height:100px;
 color:#fff;
 font-size:40px;
 background:#ccc;
 border-radius:10px;
 }
 .image-view .item {
 position:relative;
 float:left;
 height:100px;
 width:100px;
 margin:10px 10px 0 0;
 }
 .image-view .item .cancel-btn{
 position:absolute;
 right:0;
 top:0;
 display:block;
 width:20px;
 height:20px;
 color:#fff;
 line-height:20px;
 text-align:center;
 background:red;
 border-radius:10px;
 cursor:pointer;
 }
 .image-view .item img{
 width:100%;
 height:100%;
 }
 .image-view .view{
 clear:both;
 }
</style>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI