upload.vue 2.21 KB
<template>
  <CInput ref="label" :label="label">
    <slot>
      <Upload
        :max="max"
        :multiple="multiple"
        :action="action"
        :simultaneous-uploads="1"
        :value="file"
        @files-added="filesAdded"
        @file-submitted="fileSubmit"
        @file-error="fileError"
      >
      </Upload>
    </slot>
  </CInput>
</template>

<script>

import Input from './input';
import {Upload} from 'cube-ui';

import {createNamespacedHelpers} from 'vuex';

const {mapState, mapActions, mapMutations} = createNamespacedHelpers('license/form');

export default {
  name: 'CUpload',
  props: {
    value: {
      type: Array,
      default() {
        return [];
      }
    },
    label: {
      type: String
    }
  },
  data() {
    return {
      max: 1,
      multiple: false,
      action: {
        target: 'http://upload.qiniup.com/',
        data: {
          token: '',
          key: ''
        }
      },
      file: this.value
    };
  },
  methods: {
    fileSubmit(file) {
      this.action.data.token = this.token;
      this.action.data.key = Date.now() + file.name;
    },
    filesAdded(files) {
      let hasIgnore = false;
      const maxSize = 10 * 1024 * 1024; // 10M

      for (let file of files) {
        if (file.size > maxSize) {
          file.ignore = true;
          hasIgnore = true;
        }
      }

      hasIgnore && this.$createToast({
        type: 'warn',
        time: 1000,
        txt: '上传文件大于10M'
      }).show();
    },
    fileError() {
      this.$createToast({
        txt: '上传失败,请重新上传',
        type: 'error',
        mask: true,
        time: 2000
      }).show();
    },
    validate() {
      if (!this.value.length) {
        this.$refs.label.setShowError();
        return false;
      } else {
        this.$refs.label.setShowError(false);
        return true;
      }
    }
  },
  computed: {
    ...mapState(['token'])
  },
  components: {
    CInput: Input,
    Upload
  }
};
</script>

<style lang="scss" scoped>

  .cube-upload {
    /deep/ .cube-upload-btn {
      margin: 0 0;
    }

    /deep/ .cube-upload-btn-def {
      background-color: #eee;
    }

    /deep/ .cube-upload-file-status {
      font-size: 30px !important;
    }
  }

</style>