vue2-el-upload自定义图片上传、自定义回显、删除、放大

发布时间:2023年12月27日
  1. 创建一个UploadFile.vue组件文件 复制下方代码 并修改上传接口api
<template>
  <div>
    <div class="img-up">
      <div
        class="img-list"
        @mouseenter="imgShow = index"
        @mouseleave="imgShow = ''"
        v-for="(item, index) in fileList"
        :key="index"
      >
        <img :src="baseUrl + item.url.replace('file', '')" class="avatar" />
        <transition name="el-zoom-in-bottom">
          <div class="img-tools" v-show="imgShow === index">
            <i class="el-icon-view img-view  "  @click="handlePreview(item)" ></i>
            <i class="el-icon-delete img-del  " @click="beforeRemove(item)"></i></div
        ></transition>
      </div>

      <el-upload
        action="#"
        ref="upload"
        accept="image/*"
        :http-request="handleFileUpload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-upload="beforeAvatarUpload"
        :on-exceed="handleExceed"
        :limit="3"
        :show-file-list="false"
      >
        <i v-if="fileList.length < 3" class="el-icon-plus img-btn"></i>
      </el-upload>
    </div>
    <el-dialog
      append-to-body
      :visible.sync="dialogVisible"
      style="z-index: 2005"
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div> 
</template>

<script>
//修改此处api
import { uploadFile } from "@/api/jjjManage/jjjNews.js";
export default {
  props: {
  //父组件传入回显参数  ‘1.png,2.png’ 逗号隔开字符串
    value: {
      type: String,
    },
  },
  data() {
    return {
      loading: false,
      fileList: [], //深拷贝,判断重名及第一步时的文件信息展示
      baseUrl: APP_PUBLIC_CONFIG.IMG_IRL,//全局变量。拼接图片前缀
      dialogImageUrl: "",
      dialogVisible: false,
      imgShow: "",
    };
  },
  watch: {
    value(v) {
      this.fileList = this.getFlieList(v);
    },
  },
  mounted() {},
  methods: {
  //过滤回显参数,将字符串转为数组,不然不能回显
    getFlieList(list) {
      if (!list) return [];
      return list.split(",").map((e) => {
        return {
          name: e,
          url: e,
        };
      });
    },
    beforeAvatarUpload(file) {
      if (this.fileList > 3) {
        this.handleExceed(this.fileList)
        return
      }
      const isLt2M = file.size / 1024 / 1024 < 5;
      const isJPG = ["image/jpeg", "image/png"];
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 5MB!");
        return false;
      }
      if (!isJPG.includes(file.type)) {
        this.$message.error("上传图片只能是 JPG和PNG 格式!");
        return false;
      }
    },
    // 处理移除操作
    handleRemove(file, fileList) {
      this.$emit("upSuccess", this.fileList.filter((e) => e.name != file.name).map((e) => e.url).toString());
    },
    // 处理预览操作
    handlePreview(file) {
      console.log(file)
      this.dialogImageUrl = this.baseUrl + file.url.replace('file', '');
      this.dialogVisible = true;
    },
    // 处理超出图片个数操作
    handleExceed(files ) {
      this.$message.warning(
        `当前限制选择 3 个文件,本次选择了 ${files.length} 个文件 `
      );
    },
    // 移除之前的操作
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}`).then(_ => {
            this.handleRemove(file)
          });
    },
    // 处理文件上传操作
    handleFileUpload(file) {
      this.loading = true;
      let form = new FormData();
      form.append("file", file.file);
      uploadFile(form).then((res) => {
        let param = res.data.data;
        this.fileList.push({ url: param, name: file.file.name });
        //返回上传后的图片数据
        this.$emit("upSuccess", this.fileList.map((e) => e.url).toString());
        this.loading = false;
      });
    },
  },
};
</script>
<style scoped lang="scss">
.img-up {
  display: flex;
  .avatar,
  .img-btn {
    width: 100px;
    height: 100px;
    margin-right: 10px;
  }
  .img-list {
    position: relative;
    .img-tools {
      width: 100px;
      height: 100px;
      background: rgba($color: #000000, $alpha: 0.5);
      position: absolute;
      left: 0;
      top: 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .img-del,.img-view {
      color: #fff;
      font-size: 20px;
      cursor: pointer;
    }
    .img-view{
      margin-right: 15px;
    }
  }
}
.img-btn {
  width: 100px;
  height: 100px;
  border: 1px solid #eee;
  display: flex;
  justify-content: center;
  align-items: center;
}
 .transition-box {
    margin-bottom: 10px;
    width: 200px;
    height: 100px;
    border-radius: 4px;
    background-color: #409EFF;
    text-align: center;
    color: #fff;
    padding: 40px 20px;
    box-sizing: border-box;
    margin-right: 20px;
  }
</style>

  1. 组件调用
<template>
		<UploadFile :value="imgList" @upSuccess="(e) => {imgList = e;}"/>
<template />
<script>
import UploadFile from "@/components/UploadFile.vue";
export default {
	components: { UploadFile },
	data() {
	    //这里存放数据
	    return {
			imgList:''
		}
    }
}

<script/>
文章来源:https://blog.csdn.net/HandsomeGuy_/article/details/135252134
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。