element upload 图片上传 回显 及删除

element upload 图片上传 回显 及删除

目标需求

  • 图片上传
  • 图片回显
  • 可以删除图片
  • 效果图 在这里插入图片描述

实现

模板
	<el-form-item :label="$t('station.img')" prop="images">
          <el-upload
            :limit="3"
            action=""
            accept=".png, .jpg"
            show-file-list
            :on-change="handleChange"
            :on-remove="handleRemove"
            list-type="picture-card"
            :file-list="fileList"
            :auto-upload="false"
            multiple
          >
            <i slot="default" class="el-icon-plus" />
          </el-upload>
        </el-form-item>
js
  data() {
    return {
      fileList: [],//这个必须要有,用来同步组件中的fileList
      form:{
			images:[] //表单中的图片列表
		}
     }
   methods: {
   // 删除图片时候同步到表单删除
   handleRemove(file, fileList) {
      const index = this.fileList.findIndex((item) => {
        return item.uid === file.uid
      })
      this.form.images.splice(index, 1)
      this.fileList.splice(index, 1)
    },
    // 上传
    handleChange(file, fileList) {
      const isImg = (file.raw.type === 'image/png' || file.raw.type === 'image/jpeg')
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isImg) {
        this.$message.error(this.$t('common.uploadTip8'))
        this.fileList.splice(this.fileList.length, 1)
        return false
      }
      if (!isLt1M) {
        this.$message.error(this.$t('common.uploadTip3'))
        this.fileList.splice(this.fileList.length, 1)
        return false
      }
      // 同步组件中的fileList
      this.fileList = JSON.parse(JSON.stringify(fileList))
      const formData = new FormData()
      formData.append('file', file.raw)
      // 调用上传接口获取对应的http图片地址
      uploadFile(formData).then((res) => {
        this.form.images.push(res.data.fileList[0].path)
      })
    },
    // 超出图片数量时候的提示
    handleExceed(files, fileList) {
      this.$message.warning(this.$t('common.uploadTip9'))
    },
    // 回显
    getDetail() {
      getStationInfo(this.$route.query.id).then((res) => {
        this.form = res.data
        // 这一步是回显必要的,赋值给fileList
        if (this.form.images) {
          this.form.images.forEach(item => {
            this.fileList.push({
              url: item
            })
          })
        }
      })
    }
}

难点

理解 upload 中的 fileList 这个参数,需要将这个参数存起来回显,以及删除的时候找到对应删除的图片下标