el-upload上传功能的二次封装

不得不说,vue+elemenUI开发后台管理系统,就像西红柿配鸡蛋一样,真的超搭哒~~(不是说vue搭其他UI库就有缺陷,但从业务出发来说无疑是的)

el-uploa使用方法:https://element.eleme.cn/#/zh-CN/component/upload

做后台就必会遇到上传Excel文件的功能啦,所以为了方便自己的开发和简化代码,把el-upload组件化。

说了那么多,直接上代码:

<style scoped>
</style>
<template>
  <div class="upload">
    <el-upload
      :action="action"
      :data="data"
      @before-upload="handleBeforeUpload"
      v-on:on-progress="handlePreview"
      v-on:on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :show-file-list="false"
    >
      <el-button v-if="flag" slot="trigger" type="primary">Choose File</el-button>
      <el-button :type="buttonType" :loading="loading">{{buttonTxt}}<i class="el-icon-upload el-icon--right"></i></el-button>
    </el-upload>
  </div>
</template>
<script>
export default {
  props: {
    buttonTxt: {
      type: String,
      default: "Upload"
    },
    flag: {
      type:Boolean,
      default:false
    },
    action: {
      type: String,
      required: true
    },
    buttonType: {
      type: String,
      default: "primary"
    },
    data: null,
    fileSize: null, // 文件大小限制,单位为K
    uploadId: null,
    name: null,
    onSuccess: Function,
    onProgress: Function,
    beforeUpload: Function,
    fileType: null // 文件类型限制用|分隔 如png|jpg|jpeg|gif
  },
  data() {
    return {
      loading: false
    };
  },
  methods: {
    handleBeforeUpload(file) {
      const fileName = file.name;
      const ext = fileName
        .substring(fileName.lastIndexOf(".") + 1)
        .toLowerCase();
      if (this.fileType) {
        // 限制文件格式
        if (this.fileType.indexOf(ext) < 0) {
          this.$message.error("文件类型不合法,请上传" + this.fileType);
          return false;
        }
      }
      if (this.fileSize) {
        // 限制文件大小,单位为k
        if (file.size / 1024 > this.fileSize) {
          this.$message.error("文件大小限制为" + this.fileSize + "k");
          return false;
        }
      }
      this.loading = true; // 开启上传中状态
      if (this.beforeUpload) {
        const arg = [].slice.call(arguments);
        if (this.uploadId) {
          arg.push(this.uploadId);
        }
        this.beforeUpload.apply(this, arg);
      }
    },
    handlePreview(){
      this.$emit('on-progress');
    },
    handleUploadSuccess() {
      this.loading = false; // 关闭上传中状态
      if (this.onSuccess) {
        const arg = [].slice.call(arguments);
        if (this.uploadId) {
          arg.push(this.uploadId);
        }
        this.onSuccess.apply(this, arg);
      }
    },
    handleUploadError() {
      this.loading = false; // 关闭上传中状态
      this.$message.error("上传失败");
    }
  }
};
</script>

欢迎关注我的博客: https://blog.csdn.net/weixin_42323607

github地址: https://github.com/Nurtuam

多多支持!本人会持续更新哒 ❤️

Logo

前往低代码交流专区

更多推荐