vue中使用el-upload组件修改上传的图片时,每次都会自动闪过上一次的图片

引言

在进行vue后台管理系统开发的时候又遇到了这个问题,由于上次没有写文章记录,所以还是查看了之前写的项目才解决这个问题。

遇到的问题

我将上传的表单单独作为一个组件(假设为A页面),然后在另外一个页面(假设为B页面)中使用Dialog来显示这个表单。在进行修改操作的时候,A中的数据肯定是需要从B中通过props来进行传输的,然后在A中有一个图片上传的组件,那么这个图片数据肯定也是从B中传过来的。在element提供的el-upload组件中有一个参数:file-list,通过绑定这个参数可以设置其默认显示图片。

问题就出现在这里,如果我将:file-list绑定的参数通过props来进行传递(B传给A),虽然可以做到每次只显示出来我这一张图片,但是每次在打开Dialog的时候,界面会显示出上一次我打开的Dialog的图片,虽然是呈现出一个慢慢消失的效果,而且不影响效果,但是看起来不太美观。

image-20230131150913752

解决方式

我这里限制了上传数量为1

具体操作大概就是如下:

  1. 通过watch监听器去监听prop中传进来的illegalInfoImg参数(这个参数就是存储了图片的地址)
  2. 然后在watch监听器中去进行相关操作(需要判断是否符合条件,然后将illegalInfoImg参数加入到illegalInfoImgFileList中)
  3. 重置表单的时候需要将illegalInfoImg和illegalInfoImgFileList置空
  4. el-upload组件中需要绑定一个on-remove参数,在这里面写入清空illegalInfoImg即可

通过百度,我这里采用了监听器来完成操作,具体代码如下

这是我的el-upload组件

<el-form-item label="违法图片" prop="illegalInfoImg">
      <el-upload :file-list="illegalInfoImgFileList"
                 ref="upload"
                 action=""
                 :headers="illegalInfoImgUploadHeaders"
                 :data="illegalInfoImgUploadData"
                 :http-request="uploadIllegalInfoImg"
                 :before-upload="beforeUpload"
                 :on-remove="handleRemove"
                 accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                 list-type="picture-card"
                 show-file-list
                 :limit="1"> <template
        #default><i class="el-icon-plus"></i></template></el-upload>
    </el-form-item>

这是其相关方法

export default {
    
    
  name: 'UpdateIllegalInfoDialog',
  components: {
    
    },
  props: {
    
    
    formDataProps: {
    
    
      illegalInfoId: null,
      illegalInfoImg: null,
      illegalInfoPlace: "",
      illegalActId: "",
      happenTime: null,
      identityCard: "",
      carNumber: "",
      updateBy: null
    }
  },
  data() {
    
    
    return {
    
    
      formData: this.formDataProps,
      rules: {
    
    
        illegalInfoPlace: [{
    
    
          required: true,
          message: '字段值不可为空',
        }],
        illegalActId: [{
    
    
          required: true,
          message: '字段值不可为空',
        }],
      },
      illegalActIdOptions: [{
    
    
        "label": "select 1",
        "value": 1
      }, {
    
    
        "label": "select 2",
        "value": 2
      }, {
    
    
        "label": "select 3",
        "value": 3
      }],
      illegalInfoImgFileList: [],
      illegalInfoImgUploadHeaders: {
    
    },
      illegalInfoImgUploadData: {
    
    },
    }
  },
  computed: {
    
    
    getIllegalInfoImgFileListLength(){
    
    
      return this.illegalInfoImgFileList.length
    }
  },
  watch: {
    
    
    'formData.illegalInfoImg':{
    
    
      handler(newVal,oldVal){
    
    
        // this.albumCoverFileList = [];
        console.log(newVal,oldVal)
        if (oldVal == "" || oldVal == null && this.getIllegalInfoImgFileListLength==0){
    
    
          console.log(this.getIllegalInfoImgFileListLength)
          this.illegalInfoImgFileList = [{
    
    
            name: 'default',
            url: newVal
          }]
        }
      },
      immediate: true
    }
  },
  created() {
    
    
    this.getIllegalActOptions()
  },
  mounted() {
    
    },
  methods: {
    
    
    async submitForm() {
    
    
      let flag = false
      //表单验证,默认通过
      let formValidation = true
      this.$refs['vForm'].validate(valid => {
    
    
        if (!valid){
    
    
          formValidation = false
        }
        //TODO: 提交表单
      })
      if (formValidation === true){
    
    
        //这里需要使用await,否则不会等待该方法运行完成
        await updateIllegalInfo(this.formData).then(res=>{
    
    
          this.$message.success("修改成功")
          flag = true
        })
      }
      return flag
    },
    resetForm() {
    
    
      this.$refs['vForm'].resetFields()
      this.illegalInfoImgFileList = []
      this.formData.illegalInfoImg=''

    },
    getIllegalActOptions(){
    
    
      getIllegalActOptions().then(res =>{
    
    
        this.illegalActIdOptions = res.data
      })
    },
    uploadIllegalInfoImg(param){
    
    
      console.log('进入了自定义上传')
      // console.log(param.file)
      let formData = new FormData();
      formData.append('file',param.file)
      formData.append('userId',this.$store.getters.userInfo.userId)
      uploadIllegalInfoImg(formData).then(res =>{
    
    
        this.formData.illegalInfoImg = res.data
        this.$message.success("上传成功")
      })
    },
    beforeUpload(file) {
    
    
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);

      const whiteList = ["jpg", "jpeg", "png","JPG","JPEG"];

      if (whiteList.indexOf(fileSuffix) === -1) {
    
    
        this.$message.error('上传文件类型不匹配!');
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 3;

      if (!isLt2M) {
    
    
        this.$message.error('上传文件大小不能超过 3MB');
        return false;
      }
    },
    handleRemove(file, fileList){
    
    
      // this.albumCoverFileList = fileList
      this.formData.illegalInfoImg = ''
      // console.log(file, fileList);
      // console.log(this.illegalInfoImgFileList);
      // console.log(fileList.length)
      // console.log(this.illegalInfoImgFileList.length)
    }
  }
}

其中主要相关的是computedwatch中的两个方法,还有resetForm()方法中的清空执行顺序不能变,以及handleRemove()方法中的操作

总结

在解决问题后要及时记录,才能让自己在以后遇到同样问题的时候更快解决

猜你喜欢

转载自blog.csdn.net/qq_49137582/article/details/129053727