在vue3 + Element Plus 中遇到before-upload钩子不触发的问题,通常与使用方式和配置有关。

常见问题分析:

1、错误的事件绑定方式:Vue3中应使用@before-upload而非:before-upload;;

2、函数返回值的问题:没有正确返回Promise或布尔值;

3、组件配置冲突:如设置了auto-upload="false"但又未手动触发上传;

4、作用域的问题:函数未正确绑定组件的实例

官方文档截图:

正确代码实例:

<template>
  <el-upload
    class="upload-demo"
    action="https://jsonplaceholder.typicode.com/posts/"
    :file-list="fileList"
    @before-upload="handleBeforeUpload"  <!-- 注意是@符号 -->
    @on-success="handleSuccess"
    @on-error="handleError"
  >
    <el-button type="primary">点击上传</el-button>
    <template #tip>
      <div class="el-upload__tip">
        只能上传jpg/png文件,且不超过500kb
      </div>
    </template>
  </el-upload>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';

const fileList = ref([]);

// 正确的before-upload实现
const handleBeforeUpload = (file) => {
  console.log('before-upload触发了', file);
  
  // 1. 文件类型验证
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片');
    return false; // 返回false阻止上传
  }
  
  // 2. 文件大小验证
  const isLt500K = file.size / 1024 < 500;
  if (!isLt500K) {
    ElMessage.error('图片大小不能超过500KB');
    return false;
  }
  
  // 3. 也可以返回Promise进行异步验证
  // return new Promise((resolve, reject) => {
  //   if (/* 验证通过 */) resolve(true);
  //   else reject(false);
  // });
  
  return true; // 验证通过,允许上传
};

const handleSuccess = (response, uploadFile) => {
  console.log('上传成功', response, uploadFile);
  ElMessage.success('上传成功');
};

const handleError = (error) => {
  console.log('上传失败', error);
  ElMessage.error('上传失败');
};
</script>

关键注意点:

1、事件绑定方式:

        必须使用@before-upload(事件绑定)而非:before-upload(属性绑定)

2、函数返回值:

        返回false或Promise.reject()会阻止上传

        返回true或Promist.resolve()会允许上传继续

        如果没有返回值,默认会允许上传,单钩子函数仍然应该被触发

3、auto-upload配置:

        如果设置了auto-upload="false" 需要手动调用上传文件方法才会触发before-upload

                  <el-upload
                  class="upload-demo"
                  :auto-upload="false"  不加这个就会报错 
                  :on-change="onUploadVideo"
                  :multiple="false"
                  accept=".mp4,.avi"
                  :show-file-list="false"
                  drag
                  action="#"
             
                  >

4.版本兼容性:确保版本兼容        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值