vue圖片上傳組件

vue圖片上傳組件

最近在做項目的時候順便補充了一下公司項目的公共組件庫,剛剛手頭事情告一段落,就來做個筆記。

首先來看看最終效果

1.不允許刪除

這裏寫圖片描述
這裏寫圖片描述

2.允許用戶刪除(顯示刪除按鈕)

這裏寫圖片描述

實現的效果就是上圖顯示內容

接下來說說組件佈局那部分直接上代碼了

<template>
  <div class="uploadImg">
    <div class="upload-content">
      <div class="upload-title">
        <p>{{upTitle}}</p>
        <p class="show-num">{{upNum}}/{{uploadNum}}</p>
      </div>
      <ul class="img-list">
        <li class="show-img" v-for="(item, index) in imgList" :key="index">
          <img :src="item" alt="">
          <kk-icon :class="isDel == true ? '' : 'hide-del'" name="error" color="#FF685D" size="0.4rem" @click.native="delImg(index)"></kk-icon>
        </li>
        <div class="uploadSec">
          <img :src="globalPath+'img/insurance/upload.png'" alt="上傳圖標">
          <input type="file" value="" id="choose" @change='onUpload' multiple>
        </div>
      </ul>
    </div>
  </div>
</template>

上面代碼中的kk-icon是自定義的圖標組件,只是多了個接受顏色和大小的功能,你們自己寫一個替換就行了。然後動態定義它的class,實現顯隱就結束了。
隨手貼個樣式

<style lang="less" type="text/less" rel="stylesheet/less">
  .uploadImg{
    text-align: left;
    .upload-content{
      margin-left: 0.3rem;
      .upload-title{
        display: flex;
        justify-content: space-between;
        padding: 0.3rem 0.3rem 0.3rem 0;
        .show-num{
          color: #c9c9c9;
        }
      }
      .img-list{
        display: inline-block;
        margin: 0.6rem 0.3rem 0.3rem 0;
        .show-img{
          position: relative;
          display: inline-block;
          margin-right: 0.12rem;
          height: 1.3rem;
          width: 1.3rem;
          img{
            width: 100%;
            height: 100%;
          }
          .hide-del{
            display: none;
          }
          .yd-icon-error{
            position: absolute;
            top: 0;
            right: 0;
          }
        }
        .uploadSec{
          position: relative;
          display: inline-block;
          width: 1.3rem;
          height: 1.3rem;
          overflow: hidden;
          img{
            width: 100%;
            height: 100%;
          }
          #choose{
            position: absolute;
            height: 100%;
            left: 0;
            top: 0;
            opacity: 0;
          }
        }
      }
    }
  }
</style>

接下來看看實現邏輯

藉助input type="file"實現圖片選擇,是否允許多選圖片的話是通過給input的multiple屬性。(其他直接備註在裏面了)
在組件中接收父組件傳來的圖片數量限制,是否開啓刪除操作,上傳圖片地址,預覽地址等

props: ['imgNum','title','upUrl','showUrl','showDel'],

title 上傳組件的標題
imgNum 上傳圖片數量限制
upUrl 設置上傳圖片地址
showUrl設置圖片回顯地址
showDel是否允許刪除圖片
changeNum 圖片改變時,觸發父組件中的方法

當選擇圖片確定後就會觸發change,因此我在@change="onUpload" 進行上傳,上傳使用了formData

// 上傳操作
onUpload (e) {
  let photoFile = e.target
  let val = e.target.value
  // 判斷是否符合上傳條件
  if (photoFile.files.length === 0) return false
  for (let i = 0; i < photoFile.files.length; i++) {
    this.fileAdd(photoFile.files[i],i)
  }
}

上傳操作中觸發圖片後續處理方法fileAdd
因爲後臺要求拿到的圖片地址是一串字符串,所以我在下面中使用join() 進行數組轉化處理(因爲後臺不支持接受圖片數組,因此我這個上傳多選圖片之後上傳也是單張上傳)

// 添加圖片
fileAdd (file,index) {
  let csrf_token = this.getCookie('XSRF-TOKEN');
  let formFile = new FormData();
  let imgName = 'img0';
  formFile.append(imgName, file);
  formFile.append("_token", csrf_token);
  let name = file.name
  let size = file.size
  let types = '.jpg,.jpeg,.png,.gif'  //文件格式
  let fileExt = name.substring(name.lastIndexOf('.')).toLowerCase()
  let result = types.indexOf(fileExt)
  if (result < 0) {       //驗證圖片格式
    this.$dialog.toast({
      mes: '圖片格式不正確',
      timeout: 1000
    })
    return false
  }
  if (size > 1 * 1024 * 1024) {
    this.$dialog.toast({
      mes: '圖片大小不能大於1M',
      timeout: 1000
    })
    return false
  }
  if (this.fileList.length >= this.uploadNum) {
    this.$dialog.toast({
      mes: '圖片最多隻能上傳' + this.uploadNum + '張',
      timeout: 1000
    })
    return false
  }

  axios.post(this.upUrl,formFile)
    .then((res) => {
      this.upNum = this.fileList.length + 1;   //計算圖片數量
      this.fileList.push(file);                //添加進圖片數組
      let imgUrl = this.showUrl + res.data.data;  //圖片回顯地址
      let upImg = res.data.data;               //傳給後臺的圖片地址
      this.imgList.push(imgUrl);
      this.upImgList.push(upImg);
      let upImgAll = this.upImgList.join(',');
      this.$emit('input', upImgAll);
    }).catch((err) => {
      console.log(err);
  })
},

刪除圖片操作

我這刪除僅僅是對最後提交的圖片數組進行處理,並未對上傳到圖片服務器上的圖片進行移除處理

// 刪除圖片
delImg (index) {
  this.imgList.splice(index, 1);
  this.fileList.splice(index, 1);
  this.upNum = this.imgList.length;
  let imgAll = this.imgList.join(',');
  this.$emit('input', imgAll);
},

最後我在組件中監聽了圖片改變

watch: {
    imgList () {
      this.$emit('changeNum');   //觸發父組件中驗證資料是否完整的方法
    }
  },

就是這樣了,一個簡易的上傳組件(寫的不是很好,輕噴),還有可以優化的地方,後面改完再看看吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章