el-upload使用方法总结

201 阅读2分钟

项目中常用vue2,遇到了一系列的上传问题,在此记录一下

使用场景

  1. 图片回显
  2. 多图删除
  3. 设置绑定值
  4. 获取绑定值
  5. 设置只允许手机摄像头拍照问题

环境

vue版本: 2.6.x
node:16.13.0

图片回显

// 后台请求回显字段
{
  sendConfirmImages: "http://xxxxx.png,http://xxxxx2.png"
}
  <div class="camera-upload" ref="cameraUploadRef">
            <el-upload
              action=""
              :limit="10"
              :file-list="fileList"
              :auto-upload="false"
              :on-change="handleUpload"
              ref="uploadRef"
              list-type="picture-card"
              capture="camera"
              accept="image/*"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="$viewImage(file.url)">
                    <i class="el-icon-view"></i>
                  </span>
                  <span class="el-upload-list__item-delete" @click="handleOnRemove(file)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </div>
          
          
<script>
  ...
   this.fileList = sendConfirmImages?.split(',').map((i) => {
            return {
              url: i,
            }
          }) || []
  ...
</script>

多图删除

<script>
...
 handleOnRemove(file) {
      const index = this.$refs['uploadRef'].uploadFiles.findIndex((f) => f.uid == file.uid)
      if (index > -1) {
        this.$refs['uploadRef'].uploadFiles.splice(index, 1)
      }
    },
...
</script>

设置绑定值


<template>
<el-upload :on-change="handleUpload">
  ....
</el-upload>
</template>

<script>
...
data(){
  return{
    /**是否正在上传 */
      uploadFlag: false,
      /**待上传列表 */
      waitUploadList: [],
      uploadLoading: false,
  }
},
...
  
    handleUpload(file) {
      this.uploadImg()
        .then((res) => {
          const index = this.$refs['uploadRef'].uploadFiles.findIndex((i) => i.uid == file.uid)
          if (index > -1) {
            this.$refs['uploadRef'].uploadFiles[index].url = res.data.url
          }
        })
        .finally(() => this.uploadSingleFile())
    },
...
</script>

获取绑定值

<script>
...
  handleSubmit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = {
            id: this.formData.id,
            imageArr: this.$refs['uploadRef'].uploadFiles.map((i) => i.url),
          }
          ...
        }
      })
    }
...
</script>

设置只允许手机摄像头拍照问题

<script>
...
  this.$nextTick(() => {
          this.$refs['cameraUploadRef'].children[0].children[1].children[1].setAttribute('capture', 'camera')
        })
...
</script>

完整代码

<template>
  <div>
    <el-dialog
      custom-class="google-customer-info-dialog"
      :width="tableWidth"
      :title="$t('客户信息')"
      destroy-on-close
      append-to-body
      :visible.sync="show"
      :before-close="cancel"
    >
      <el-form @submit.native.prevent ref="formRef" :model="formData" size="mini" label-width="80px">
        <el-form-item label="客人:" prop=""> {{ formData.receiveName }} </el-form-item>
        <el-form-item label="邮编:" prop=""> {{ formData.receivePostcode }} </el-form-item>
        <el-form-item label="地址:" prop=""> {{ formData.address }} </el-form-item>
        <el-form-item label="包裹号:" prop=""> {{ formData.packageNo }} </el-form-item>
        <el-form-item label="状态:" prop="">
          <!-- 1 待配送 2 配送中 3 已完成 (状态2 无用) -->
          <div v-if="formData.status == 1" :style="{ color: $randomColor(formData.status) }">{{ $t('待配送') }}</div>
          <div v-if="formData.status == 2" :style="{ color: $randomColor(formData.status) }">{{ $t('配送中') }}</div>
          <div v-if="formData.status == 3" :style="{ color: $randomColor(formData.status) }">{{ $t('已完成') }}</div>
        </el-form-item>
        <el-form-item label="拍照确认:">
          <div class="camera-upload" ref="cameraUploadRef">
            <el-upload
              :disabled="formData.status == 3"
              action=""
              :limit="10"
              :file-list="fileList"
              :auto-upload="false"
              :on-change="handleUpload"
              ref="uploadRef"
              list-type="picture-card"
              capture="camera"
              accept="image/*"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="$viewImage(file.url)">
                    <i class="el-icon-view"></i>
                  </span>
                  <span class="el-upload-list__item-delete" v-if="formData.status != 3" @click="handleOnRemove(file)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="负责人:" prop="">
          {{ formData.nickNames }}
        </el-form-item>
      </el-form>
      <div slot="footer">
        <div>
          <el-button
            @click="handleSubmit"
            type="success"
            :disabled="formData.status == 3"
            v-hasPermi="['distribution:googleRouteShipments:confirmShipment']"
          >
            {{ $t('确认送达') }}
          </el-button>
          <el-button @click="cancel">
            {{ $t('关闭') }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

import { confirmShipment } from '@/api/orderManage/myDispatch'

export default {
  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: () => ({}),
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        key1: [{ required: true, message: this.$t('请输入'), trigger: 'blur' }],
      },
      fileList: [],
      /**是否正在上传 */
      uploadFlag: false,
      /**待上传列表 */
      waitUploadList: [],
      uploadLoading: false,
    }
  },
  computed: {
    /**@returns {any} */
    tableWidth() {
      return this.isMobile() ? '350px' : '600px'
    },
  },
  mounted() {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.fileList =
          this.formData.sendConfirmImages?.split(',').map((i) => {
            return {
              url: i,
            }
          }) || []
        this.$nextTick(() => {
          this.$refs['cameraUploadRef'].children[0].children[1].children[1].setAttribute('capture', 'camera')
        })
      }
    },
  },
  methods: {
    uploadImg(data) {
      return request({
        url: '/system/oss/uploadTemp',
        method: 'post',
        data,
      })
    },
    // 上传单个文件
    uploadSingleFile() {
      /**上传结束 */
      if (!this.waitUploadList.length) {
        // 正在上传状态改为false
        this.uploadFlag = false
        this.uploadLoading?.close()
        this.$message({ type: 'success', message: '上传完成!' })
        return
      }
      const formData = new FormData()
      const file = this.waitUploadList.shift()
      formData.append('file', file.raw)
      formData.append('type', '12')
      formData.append('businessId', this.formData.id)
      this.uploadImg(formData)
        .then((res) => {
          const index = this.$refs['uploadRef'].uploadFiles.findIndex((i) => i.uid == file.uid)
          if (index > -1) {
            this.$refs['uploadRef'].uploadFiles[index].url = res.data.url
          }
        })
        .finally(() => this.uploadSingleFile())
    },
    handleUpload(file) {
      // 如果正在上传中,直接添加到待上传列表中
      if (this.uploadFlag) {
        return this.waitUploadList.push(file)
      }
      this.uploadLoading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      this.uploadFlag = true
      this.waitUploadList = [file]
      this.uploadSingleFile()
    },
    handleOnRemove(file) {
      const index = this.$refs['uploadRef'].uploadFiles.findIndex((f) => f.uid == file.uid)
      if (index > -1) {
        this.$refs['uploadRef'].uploadFiles.splice(index, 1)
      }
    },

    getList() {},

    handleSubmit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = {
            id: this.formData.id,
            imageArr: this.$refs['uploadRef'].uploadFiles.map((i) => i.url),
          }
          confirmShipment(data).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })
              this.cancel()
              this.$emit('getList')
            }
          })
        }
      })
    },
    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.camera-upload {
  width: 100%;
  max-height: 300px;
  overflow: auto;
  $itemWidth: 110px;
  ::v-deep .el-upload-list__item {
    width: $itemWidth;
    height: $itemWidth;
  }
  ::v-deep .el-upload--picture-card {
    width: $itemWidth;
    height: $itemWidth;
    position: relative;
    .el-icon-plus {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>