el-upload上传必填验证

发布时间 2023-10-30 11:38:19作者: 小虾米吖~
 <el-form-item label="excel文件" prop="file">
          <el-upload style="display: inline-block;margin-left: 10px"
                    class="upload-demo"
                     ref="upload"
                     :file-list="addForm.file"
                     accept=".xls,.xlsx"
                     :data="addForm"
                     :auto-upload="false"
                     :action="uploadFileUrl"
                     :headers="headers"
                     :show-file-list="false"
                     :on-success="handleUploadSuccess"
                     :on-change="changeFile"
                     >
            <span v-if="curName">{{curName}}</span>
            <el-button type="primary" icon="" v-else>选文件</el-button>
          </el-upload>
        </el-form-item>

data部分

 addForm: {
        file:[],
        annexUrl:''
      },
      rules: {
        file: [
          {required: true, message: '导入文件不能为空'}
        ]
      },

 

script部分

changeFile(file,fileList){
      this.curName = file.name;
      if (fileList.length > 0) {
        this.addForm.file = fileList;
        this.$refs.addForm.clearValidate('file'); //清除文字校验
      }
    },
 // 导入:提交表单
    submitComplete() {this.$refs.addForm.validate(async (valid) => {
        if (valid) {if(typeof this.addForm.file == 'object'){  // 验证加的file可以删除,也可留着。
            delete this.addForm.file;
          }
          this.$refs.upload.submit(); // upload提交
        }
      });
    },