Element-UI 踩坑填坑

关于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)
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容