动态获取对象,文件上传组件

export function GetProperty(obj, str) {
    str = str.replace(/\[(\w+)\]/g, ".$1"); // 处理数组下标
    let arr = str.split(".");
    for (let i in arr) {
        obj = obj[arr[i]] || "";
    }
    return obj;
}

使用:

 state.tableData = GetProperty(
              res,
              props.config.requestState.dataKey
            )

vue2的文件上传组件:

<template>
  <div class="component-upload-image">
    <el-upload
        ref="uploadRef"
        :drag="drag"
        :disabled="disabled"
        :multiple="false"
        :action="postUrl"
        :list-type="listType ? listType : 'picture-card'"
        :on-success="handleUploadSuccess"
        :before-upload="handleBeforeUpload"
        :limit="limit"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-change="handleChange"
        name="file"
        :on-remove="handleRemove"
        :before-remove="handlerBeforeRemove"
        :show-file-list="true"
        :headers="headers"
        :with-credentials="true"
        :file-list="fileList"
        :on-preview="handlePictureCardPreview"
        :class="{
        hide: fileList.length >= this.limit || type == 3,
        avator_small: smallStyle,
        avator_mini: miniStyle,
        avator_radius: radiusStyle,
      }"
        style="margin-right: 20px"
    >
      <el-icon v-if="drag" class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div v-if="drag" class="el-upload__text">
        拖拽或 <em>点击上传文件</em>
      </div>
      <template v-if="showTip" #tip>
        <!-- 上传提示 -->
        <div class="el-upload__tip" slot="tip">
          请上传
          <template v-if="fileSize">
            大小不超过
            <b style="color: #f56c6c">{{ fileSize }}MB</b>
          </template>
          <template v-if="fileType">
            格式为
            <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
          </template>
          的文件
        </div>
      </template>
      <el-icon v-if="!drag" :class="`el-icon-plus`">
        <Plus/>
      </el-icon>
    </el-upload>
    <!-- :http-request="handlerPost" -->

    <div v-if="tipText.length > 0">
      <div
          :style="`color: #999;${
          miniStyle && 'font-size:12px;line-height:18px'
        };white-space:nowrap; `"
          v-for="text in tipText"
          :key="text"
      >
        {{ text }}
        <br/>
      </div>
    </div>

    <el-dialog
        v-model:visible="dialogVisible"
        title="预览"
        width="800"
        append-to-body
    >
      <img
          :src="dialogImageUrl"
          style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from '@/utils/auth';

export default {
  props: {
    value: [String, Object, Array],
    drag: {
      type: Boolean,
      default: false,
    },
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    type: {
      type: Number,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg'],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    uploadImgUrl: {
      type: String,
      default: '/system/user/profile/upload',
    },
    tipText: {
      type: Array,
      default: [],
    },
    smallStyle: {
      type: Boolean,
      default: false,
    },
    miniStyle: {
      type: Boolean,
      default: false,
    },
    radiusStyle: {
      type: Boolean,
      default: false,
    },
    listType: {
      type: String,
    },
  },
  created () {
    console.log(this.disabled, '1111111')
    console.log(window.location.origin)
  },
  data () {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      hideUpload: false,
      postUrl: '/tempFile/upload',
      // postUrl:
      //     window.location.origin +
      //     (process.env.VUE_APP_BASE_API === '/'
      //         ? ''
      //         : process.env.VUE_APP_BASE_API) +
      //     (this.uploadImgUrl || '/system/user/profile/upload'), // 上传的图片服务器地址
      //   headers: {
      // Authorization: 'Bearer ' + getToken()
      //   },
      fileList: [],
      uploadFlag: false,
    }
  },
  watch: {
    value: {
      handler (val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',')
          // 然后将数组转为对象数组

          this.fileList = list.map((item) => {
            if (typeof item === 'string') {
              item = { name: item, url: item }
            }
            return item
          })
        } else {
          this.fileList = []
          return []
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip () {
      return this.isShowTip && (this.fileType || this.fileSize)
    },
  },
  methods: {
    // // 请求单独处理
    // handlerPost: (obj) => {
    //   console.log(obj, "obj");
    // },
    // 更改
    handleChange (file, fileList) {
      console.log(file, fileList, this.fileList, 'handleChange')
      // this.fileList = [];
    },
    // 删除图片
    async handlerBeforeRemove () {
      if (this.uploadFlag) {
        this.uploadFlag = false
        return true
      }
      // console.log(this.uploadFlag);
      await this.$confirm('是否删除该文件?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
    },
    handleRemove (file, fileList) {
      console.log(this.$refs.uploadRef, 'uploadRef')
      const findex = this.fileList.map((f) => f.name).indexOf(file.name)

      if (findex > -1) {
        this.fileList.splice(findex, 1)
        this.$emit('input', this.listToString(this.fileList))
      }
    },
    // 上传成功回调
    handleUploadSuccess (res, file, fileList) {
      console.log(res, 'handleUploadSuccess')
      console.log(file, 'file')
      if (res.code === 200) {
        this.uploadList.push({
          name: res.data.url,
          url: 'https://cdn2.linjiaxiaoda.com/' + res.data.url,
        })
        if (this.uploadList.length === this.number) {
          this.fileList = this.fileList.concat(this.uploadList)
          this.uploadList = []
          this.number = 0
          this.$emit('input', this.listToString(this.fileList))
          this.$modal.closeLoading()
        }
      } else {
        this.$message.error('文件上传失败!')
        // this.$refs.fileList =
        this.number--
        this.$refs.uploadRef.fileList = [...this.fileList]
        console.log(
            file,
            fileList,
            this.fileList,
            this.$refs.uploadRef,
            'fileList'
        )

        this.$modal.closeLoading()
      }
    },
    // 上传前loading加载
    handleBeforeUpload (file) {
      console.log(file, 'file')
      let isImg = false

      if (this.fileType.length) {
        let fileExtension = ''

        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) {
            return true
          }
          if (fileExtension && fileExtension.indexOf(type) > -1) {
            return true
          }
          return false
        })
      } else {
        isImg = file.type.indexOf('image') > -1
      }

      if (!isImg) {
        this.$modal.msgError(
            `文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`
        )
        this.uploadFlag = true
        return false
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize

        if (!isLt) {
          this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize} MB!`)
          this.uploadFlag = true
          return false
        }
      }
      this.$modal.loading('正在上传文件,请稍候...')
      this.number++
    },
    // 文件个数超出
    handleExceed () {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`)
    },
    // 上传失败
    handleUploadError () {
      this.$modal.msgError('上传文件失败,请重试')
      this.$modal.closeLoading()
    },
    // 预览
    handlePictureCardPreview (file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 对象转成指定字符串分隔
    listToString (list, separator) {
      let strs = ''

      separator = separator || ','
      for (let i in list) {
        strs += list[i].url + separator
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : ''
    },
  },
}
</script>
<style scoped lang="scss">
.component-upload-image {
  display: flex;
  align-items: flex-end;
}

// .el-upload--picture-card 控制加号部分
:deep(.el-upload--picture-card) {
  &.hide {
    display: none;
  }
}

// 去掉动画效果
:deep(.el-list-enter-active),
:deep(.el-list-leave-active) {
  transition: all 0s;
}

:deep(.el-list-enter),
.el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}

.avator_small {
  :deep(.el-upload-list__item),
  :deep(.el-upload),
  :deep(.el-upload--picture-card) {
    position: relative;
    width: 75px !important;
    height: 75px !important;

    .el-icon-plus {
      position: absolute;
      top: 28px;
      left: 28px;
      font-size: 16px;
    }
  }
}

.avator_mini {
  :deep(.el-upload-list__item),
  :deep(.el-upload),
  :deep(.el-upload--picture-card) {
    position: relative;
    width: 60px !important;
    height: 60px !important;

    .el-icon-plus {
      position: absolute;
      top: 23px;
      left: 23px;
      font-size: 12px;
    }
  }
}

.avator_radius {
  :deep(.el-upload) {
    border-radius: 50%;
  }
}

</style>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值