element-ui 使用el-upload , before-upload函数不好使

在使用el-upload这个组件的时候,业务是需要传其他参数给后台,所以校验写在before-upload中,在before-upload中直接返回true或者是false依然会发文件给后台

参数 说明 类型 可选值 默认值
on-progress 文件上传时的钩子 function(event, file, fileList) — —
on-change 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用 function(file, fileList)
before-upload 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。 function(file)
auto-upload 是否在选取文件后立即进行上传 boolean true

这里有个地方需要注意:
before-upload 是上传前的校验,因此auto-upload必须为true

解决方式:
我这里是采用在函数中返回一个promise来解决的:

<template>
	<el-upload
	  class="avatar-uploader"
	  action="https://xxx.xxx.com/xxx/xxx"
	  :show-file-list="false"
	  :on-success="handleAvatarSuccess"
	  :before-upload="beforeAvatarUpload">
	  <img v-if="imageUrl" :src="imageUrl" class="avatar">
	  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
	</el-upload>
</template>
<script>
export default {
	data() {
      return {
        imageUrl: ''
      };
    },
	methods: {
		beforeAvatarUpload (file) {
	      return new Promise(async (resolve, reject) => {
	      	// 失败
	        if ('xxx' !=0) {
	          reject()
	        } else {
	        	// 成功
	        	resolve()
			}
	      })
	    },
	    handleAvatarSuccess(res, file) {
	        this.imageUrl = URL.createObjectURL(file.raw);
	    }
	 }
 }
 </script>

你可能感兴趣的:(el-upload,上传)