关于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()
}
el-input 实现数字金额输入
可能会首先想到 <el-input-number>,因为从语义上来说它就该是为数字输入专门设计的组件,但是真正应用的时候就会发现问题:没有实现限制用户输入的效果,只在失焦的时候才把非法字符去除,即便讲出一堆的科学道理也无法这说服用户,所以还是自己写吧,就用 <el-input>。
<el-input
v-model="model"
@input="inputHandle"
@change="changeHandle"
/>
const model=ref('')
const props = defineProps(['decimal', 'decimalPad'])
const emits = defineEmits(['change', 'input'])
function inputHandle(value){
// 使用正则表达式限制小数点后两位
let temp=(value||'').toString()
.replace(/^-{2,}(.*)$/, '-$1')
.replace(/[^0-9.-]/g, '')
.replace(/(\d+.?)-(\d?)/g, '$1$2')
.replace(/(\..*)\./g, '$1')
.replace(/^\-?0{2,}$/, '0');
// 小数位数为0则不允许小数点
if(!props.decimal){
temp=temp.replace(/\./g, '')
}
const parts = temp.split('.');
if (parts[1] && parts[1].length > props.decimal) {
temp=[
parts[0],
parts[1].substring(0, props.decimal)
].join('.')
}
model.value=temp
emits('input', temp)
}
function changeHandle(value){
let temp=parseFloat(value).toString()
temp=temp==='NaN'?'':temp
if(temp){
const parts=temp.split('.')
if(props.decimalPad){
// 补充小数位
temp=[
parts[0],
(parts[1]||'').padEnd(props.decimal,'0')
].filter(val=>val).join('.')
}
}
model.value=temp
emits('change', temp)
}