2.Upload上传组件注意点

版权声明:所有原创文章未经本人同意不得随意转载,谢谢 https://blog.csdn.net/tangcc110/article/details/82859881

1.自定义上传,如果没有触发上传按钮(即选中图片),则this.$refs.upload.submit() 

不会触发:http-request = "httpRequest"事件 。只有选中图片才能触发this.$refs.upload.submit() 。

<el-form-item :label="upload_lable" :label-width="formLabelWidth">
  <el-upload class="upload-demo" ref="upload" :limit="upload_limit" :auto-upload="false" :http-request="httpRequest" action=""  :on-change="filechange" :on-remove="handleRemove" :file-list="form.fileList" list-type="picture">
    <el-button size="small" type="primary">点击选择</el-button>
    <div slot="tip" class="el-upload__tip">只能上传1张jpg/png文件,且不超过500kb</div>
  </el-upload>
</el-form-item>

<div slot="footer" class="dialog-footer">
  <el-button @click="dialogFormVisible = false">取 消</el-button>
  <el-button type="primary" @click="commitSave">确 定</el-button>
</div>
filechange(file, fileList) { // 如果没有选取文件,可以加个字段来控制流程
  if (file.name) {
    this.upload_flag = true;
  }
},
//触发 httpRequest 事件
commitSave(){ // 点确定时触发事件
  if(this.upload_flag){
    this.$refs.upload.submit();
  }else{ // 不传图片,直接调用
    this.$refs['form'].validate((valid) => {
      if (valid) {
        this.loading = true;
        if(this.dialogTitle == "新增风格"){
          this.form.id = '';
        }else{}
        var fd = new FormData();// FormData 对象
        fd.append("image_file", '');// 文件对象
        // 其他参数
        fd.append("id", this.form.id);
        fd.append("sort", this.form.sort);
        fd.append("name", this.form.name);
        updateStyle(fd).then(rsp => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.getInitData();
          this.clearForm();
          this.loading = false;
          this.dialogFormVisible = false;
        }).catch(error => {
          this.loading = false;
        })
      } else {
        console.log('error httpRequest submit!!');
        return false;
      }
    });
  }

},
httpRequest(param) { // param是自带参数。 this.$refs.upload.submit() 会自动调用httpRequest方法.在里面取得file
  this.$refs['form'].validate((valid) => {
    if (valid) {

      this.loading = true;
      if(this.dialogTitle == "新增风格"){
          this.form.id = '';
      }else{}

  var fileObj = param.file; // 相当于input里取得的files
  var fd = new FormData();// FormData 对象
  fd.append("image_file", fileObj);// 文件对象
  // 其他参数
  fd.append("id", this.form.id);
  fd.append("sort", this.form.sort);
      fd.append("name", this.form.name);
      updateStyle(fd).then(rsp => { // 直接提交给后台。
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.getInitData();
        this.clearForm();
        this.loading = false;
        this.dialogFormVisible = false;
      }).catch(error => {
        this.loading = false;
      })
    } else {
      console.log('error httpRequest submit!!');
      return false;
    }
  });
},

猜你喜欢

转载自blog.csdn.net/tangcc110/article/details/82859881