el-upload 组件总结

  最近因为项目需求是一个问卷功能,问卷当中有需要上传文件的题型需求,因为上传的是图片还需要能够预览,所以就开始想自己写个上传文件的功能。自己写的当时也在ie上遇到了一些兼容问题。

<div class="window">
  <input type="file" class="filepath files" :id="'ques'+index" style="opacity: 0;" @change="uploadImgpic($event,item)">
  <i class="el-icon-upload" v-if="!item.value"></i>
  <div class="upload-txt" v-if="!item.value">点击上传文件</div>
</div>

let formData = new FormData();
formData.append("file",files);
formData.append("quest_item_id",item.id);
this.$store.dispatch("questEnc",formData).then(res=>{
  e.target.value = "";
  if(res.data.code == 200){ 
    item.config.loading = false;
    let data = res.data.data;
    console.log(data)
    item.value = data.cover_img_url;
    item.src = data.src;
    item.name = data.name;
    item.fileid = data.id;
    return
  }
}).catch(err=>{
  console.log(err,22)
}).finally(()=>{
  item.value = "";
  item.config.loading = false;
})

  自己写的这个功能,不知道什么原因在ie上请求直接被catch捕获,报 Unhandled promise rejection TypeError: 对象不支持“entries”属性或方法 错误。

el-upload 组件

  直接上代码:

<el-upload
  :id="'quest'+index"
  :ref="'quest-upload'+index"
  class="avatar-uploader"
  action="/api/v1/user/quest_enc"
  :show-file-list="false"
  :on-success="$event=>handleAvatarSuccess($event,item)"
  :on-error="$event=>uploaderr($event,item)"
  :data="{quest_item_id:item.id,token:token?token:temtoken}"
  :before-upload="$event=>beforeAvatarUpload($event,item)">
  <i v-if="!item.value"  class="el-icon-upload"></i>
  <div class="upload-txt" v-if="!item.value" slot="tip">点击上传文件</div>
</el-upload>
  • 组件的 Methods 方法可以使用vue的ref属性来调用。

  在使用过程中遇到的问题,对于上传成功,失败,上传之前的钩子需要传入一些额外的参数(重点)

  • 对于这些钩子函数,如果不需要传入额外的参数的话,默认就不需要小括号,直接绑定就可以,$event参数默认是可以获取到的。
  • 如果需要传入一些业务需要的参数,同时还需要获取到$event参数,这里有一些小坑,正常我们都会以这种方式传:

  :on-success=handleAvatarSuccess($event,item)

  • 这样传的话,在对应的钩子方法里是无法获取到 $event 参数的,获取到的值是 undefined

  • 解决方法是:采用回调的方式去传 $event 参数。(除非不带小括号)

  :on-success="$event=>handleAvatarSuccess($event,item)"

原文地址:https://www.cnblogs.com/aloneer/p/14637995.html