vue配合element-ui实现图片多张上传和删除

实现图片多张上传和删除

  <div class="title1" style="padding-left: 10px">
    文字信息 ( 最多****)
  </div>
  <div class="imgList">
    <div class="imgContent" v-if="imageUrl.length">
      <div
        class="list"
        v-for="(item, index) in imageUrl"
        :key="index"
        style="margin-right: 10px"
      >
        <img
          style="display: inline-block; width: 108px; height: 108px"
          :src="item"
          alt
        />
        <span class="remove" @click="removeImg(index)">
          <i class="el-icon-delete"></i>
        </span>
      </div>
    </div>
    <el-upload
      v-show="showUpload"
      ref="addUpload"
      class="avatar-uploader"
      action
      :show-file-list="false"
      accept="image/jpeg, image/jpg, image/png"
      :auto-upload="false"
      :on-change="uploadMap"
    >
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>

这里是js

   data() {
     
    return {
     
    	imageUrl: [],
    	showUpload:false
    }
   }
    //图片删除
    removeImg(index) {
     
      this.imageUrl.splice(index, 1);
      if (this.imageUrl.length == 6) {
     
        this.showUpload = false;
      } else {
     
        this.showUpload = true;
      }
    },
    //图片上传
    uploadMap(file) {
     
      if (file) {
     
        let formData = new FormData();
        formData.append("file", file.raw); //uploadImg是上传图片接口函数 我这里是封装在了全局组件里面
        uploadImg(formData).then((res) => {
     
          this.imageUrl.push(res.data.url);
          if (this.imageUrl.length == 6) {
     
            this.showUpload = false;
          } else {
     
            this.showUpload = true;
          }
        });
      }
    },

这里是css样式

.imgList .imgContent {
     
  display: flex;
}
.imgList .list {
     
  position: relative;
}
.imgList .list .remove {
     
  font-size: 56px;
  color: #fff;
  line-height: 108px;
  text-align: center;
  width: 108px;
  height: 108px;
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
}
.imgList .list:hover .remove {
     
  display: block;
}
.imgList {
     
  display: flex;
  padding-left: 10px;
}

最后给大家看一下外部封装的上传接口函数

import request from '@/utils/request'
/**
 * 图片上传
 * @param {*} data
 */
export function uploadImg(data) {
     
  return request({
     
    url: '/index/upload/uploadOne',
    method: 'post',
    data:data,
    headers: {
     
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}

我会在编程中遇到一些有意思的东西和比较常用的一些工具 希望大家多多支持 一键三连哈~~

你可能感兴趣的:(vue,elementui)