upload.vue 2.84 KB
<template>
  <CInput ref="label" :label="label">
    <slot>
      <div @click="showImagePreview">
        <Upload
          :max="max"
          :multiple="multiple"
          :action="action"
          :simultaneous-uploads="1"
          :value="file"
          @files-added="filesAdded"
          @file-submitted="fileSubmit"
          @file-error="fileError"
          @file-success="fileSuccess"
          @file-removed="fileRemove"
        >
        </Upload>
      </div>
    </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 = '/license/' + 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;
      }
    },
    showImagePreview() {
      if (this.value && this.value[0] && this.value[0].response && this.value[0].response.key) {
        this.$createImagePreview({
          imgs: ['//img01.yohoboys.com/' + this.value[0].response.key + '?imageView2/2/w/450/q/20']
        }).show();
      }
    },
    fileSuccess(file) {
      file.name = file.response.key;
      this.$emit('file-change');
    },
    fileRemove(file) {
      this.$emit('file-change');
    }
  },
  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;
      color: black;
    }
  }

</style>