写一个自己非常喜欢的单文件上传(封装自el-upload)

80 阅读1分钟
<template>
  <div class="m-upload">
    <el-upload
      v-bind="$attrs"
      v-on="$listeners"
      :accept="fileType"
      action=""
      :show-file-list="false"
      :auto-upload="false"
      :multiple="false"
      :on-change="fileHandleChange"
      :disabled="upLoadDisabled"
    >
      <el-button size="small" type="primary" v-if="buttonText.length != 0">{{
        buttonText
      }}</el-button>
      <slot name="in-upload"></slot>
      <div slot="tip">
        <slot name="tip-solt"></slot>
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: "XUpload",
  props: {
    // 上传文件大小限制
    fileCapacity: {
      type: Number,
      default: () => 2,
    },
    // 上传文件类型限制
    fileType: {
      type: String,
      default: () => ".jpg,.png,.jpeg",
    },
    buttonText: {
      type: String,
      default: () => "",
    },
    upLoadDisabled: {
      type: Boolean,
      default: () => false,
    },
  },
  computed: {},
  mounted() {},

  methods: {
    // 文件触发
    async fileHandleChange(file) {
      const list = file.name.split(".");
      const isFile = this.fileType.includes(list[1]);
      const isSize = file.size / 1024 / 1024 < this.fileCapacity;
      if (!isFile) {
        return this.$message.error(`请选择${this.fileType}文件上传`);
      }
      if (!isSize) {
        return this.$message.error(`文件不得大于${this.fileCapacity}M!`);
      }
      this.$emit("uploadFile", file.raw);
    },
  },
};
</script>

<style lang="scss">
.m-upload {
  display: inline-flex;
}
</style>

用于单文件上传,上传后会获取当前文件的相关信息,其它的封装并没有。