elementui 多图上传限制数量隐藏加号

发布时间 2023-04-24 09:44:10作者: jqynr

参考:https://blog.csdn.net/qq_41555695/article/details/93491140

完整的elementui多图上传组件

<template>
  <el-upload
    :action="MixinUploadAllApi"
    :headers="headers"
    list-type="picture-card"
    :file-list="fileList"
    :on-success="handleSuccess"
    :on-remove="handleRemove"
    :before-upload="beforeAvatarUpload"
    :limit="limit"
    multiple
    :class="{ disabled: uploadDisabled }"
  >
    <i slot="default" class="el-icon-plus"></i>
  </el-upload>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "ImageUpload",
  data() {
    return {
      disabled: false,
      MixinUploadAllApi: process.env.VUE_APP_BASE_API + "/system/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: this.imgs,
      uploadDisabled: false,
    };
  },
  props: {
    //
    imgs: {
      type: Array,
      default: () => {},
    },
    // 大小限制(KB)
    fileSize: {
      type: Number,
      default: 1024,
    },
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    change: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    change: function (newval) {
      if (newval) {
        this.fileList = this.imgs;
      }
    },
  },
  methods: {
    // 图片上传成功的函数
    handleSuccess(response, file, fileList) {
      this.returnBack(fileList);
    },
    //图片移除函数
    handleRemove(file, fileList) {
      this.returnBack(fileList);
    },
    /** 附件图片上传之前的校验 可公用*/
    beforeAvatarUpload(file) {
      const isType =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      const isLt1M = file.size / 1024 < this.fileSize;
      if (!isType) {
        this.$message.error("上传图片只能是 JPG/JPEG/PNG 格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传图片大小不能超过 400kb!");
      }
      return isType && isLt1M;
    },

    // 返回
    returnBack(fileList) {
      let arr = [];
      fileList.forEach((element) => {
        arr.push(element.response ? element.response.url : element.url);
      });
      this.$emit("changeImgsAct", arr);
      // 隐藏加号
      if (fileList.length >= this.limit) {
        this.uploadDisabled = true;
      } else {
        this.uploadDisabled = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/* 控制加号部分 */
.disabled ::v-deep .el-upload--picture-card {
  display: none !important;
}
</style>