关于UI库,绝对有更好的选择,无奈element-ui似乎“深入人心”,我经历过的项目大多不愿意“冒险”尝试其他优秀的UI库,无奈踩了很多坑,用功能上的、规范上的,不少让人膈应的用法,本文对 Element Plus (Vue3)使用中遇到的问题一一列举,不定期更新。
el-upload 实现文件替换功能
<el-upload> 本身不直接支持文件替换,索性利用它对外暴露的方法可以手撸一个,大致思路及代码(伪)如下:
在 #file 插槽中放置按钮:
<el-upload
ref="uploader"
:accept="props.accept.join(',')">
<template #file="{ file, index }">
<template v-if="props.replaceable">
<el-icon @click="()=>refs.replaceFileInput?.click()" title="重新上传"><Switch /></el-icon>
<!-- 一个隐藏的 input[type=file] 同时绑定监听事件及 accept -->
<input
type="file"
ref="replaceFileInput"
v-show="false"
:accept="props.accept.join(',')"
@change="(event) => replaceHandle((event.target as HTMLInputElement).files?.[0], file)"/>
</template>
<template>
</el-upload>
重点是绑定在 input[type=file] 上的 change 事件的 replaceHandle 方法:
// 当选中文件后触发
function replaceHandle(file:UploadRawFile,beReplacedFile:UploadRawFile){
console.log('replaceHandle',file,index)
// 以下便是组件原生暴露的方法
refs.uploader?.handleRemove(beReplacedFile)
refs.uploader?.handleStart(file)
refs.uploader?.submit()
}