elementUI-upload

<template>
  <ui-row :gutter="20" class="p_botm">
    <ui-col :span="24">
      <p class="p_title">{{title}}({{num}}张)</p>
    </ui-col>
    <ui-col :span="24">
      <ui-upload
        class="avatar-uploader"
        action="/hechuang-erp/file/upload"// 上传的接口
        :data="param"// 上传时附带的参数
        :show-file-list="true"// 在页面显示上的传图片
        list-type="picture-card"// 文件列表的类型 =>类型:text/picture/picture-card
        :limit="num"// 限制上传的个数
        :on-exceed="handleExceed"// 超过限制个数时提醒用户
        :on-success="handleAvatarSuccess"图片上传成功时返回(response, file, fileList) filr:存放返回的url
        :on-remove="deleteImgUrl"// 删除图时返回 (file, fileList) 获取fileId
        :before-upload="beforeAvatarUpload"// 上传图片之前判断类型和大小
        name="file">//  文件字段名 默认:file
        <img v-if="show" :src="src" class="avatar">// v-if ='false' 页面才会正常
        <i v-if="!show" class="el-icon-plus"></i>
      </ui-upload>
    </ui-col>
  </ui-row>
</template>

<script>
  import http from '@/api/user'
  export default {
    components: {},
    // 父组件构建dept对象传入(内容id和deptName)
    props: ['getUserId', 'getTitle', 'getNum', 'getType'],
    methods: {
      handleAvatarSuccess(response, file, fileList) {
        this.src = file.url
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 ${this.num}个文件,本次选择了 ${(files.length + fileList.length) - 1} 个文件,共选择了 ${files.length + fileList.length} 次文件`)
      },
      deleteImgUrl(file, fileList) {
        console.info(file.response)
        if (file.response) {
          http
          .deleteImg(file.response.data.fileId).then(r => {
            this.$message({type: 'success', message: '删除成功'})
          }).catch(r => {})
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
          this.$message.error(`上传${this.getTitle}图片只能是 JPG 格式!`)
        }
        if (!isLt2M) {
          this.$message.error(`上传${this.getTitle}图片大小不能超过 2MB!`)
        }
        return isJPG && isLt2M
      }
    },
    mounted() {
    },
    data() {
      return {
        show: false,
        src: null,
        title: this.getTitle,
        num: this.getNum,
        arr: [],
        param: {
          userId: this.getUserId,
          fileType: this.getType
        }
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .p_botm {
    padding-bottom: 10px;
  }
  .p_title {
    padding-bottom: 5px;
  }
</style>

  

原文地址:https://www.cnblogs.com/LWJ-booke/p/8570438.html