分别限制el-input输入框中英文个数

需求:修改主标题限制中文30个字符,英文60个字符;副标题限制中文40个字符,英文80个字符

//主标题
<el-input
    v-model="navigateItem.title"
    @input="(val)=> {handleInput(val,'title')}"></el-input>
 
//副标题
<el-input
    v-model="navigateItem.subTitle"
    @input="(val)=> {handleInput(val,'subTitle')}"></el-input>


handleInput(value, key) {
      let index = 0
      const selfValue = value.split('')
      let count = 0
      let charCode = -1
      let titleLength
      // 主标题和副标题限制不同长度
      if (key === 'title') {
        titleLength = 30
      } else if (key === 'subTitle') {
        titleLength = 40
      }
      // 遍历输入字符
      selfValue.forEach((item, _index) => {
        if (index) {
          return
        }
        charCode = item.charCodeAt(item)
        // 判断中英文字符
        if (charCode >= 0 && charCode <= 128) {
          count += 1
        } else {
          count += 2
        }
        if (count > titleLength) {
          index = _index
        }
      })
      // 输入框截断字符
      if (index) {
        this.navigateItem[key] = value.substring(0, index)
      }
    }

后续导师希望做一个小demo把forEach换成reduce

一开始思路如下:

selfValue.reduce((pre,cur,_index)=>{
    if(pre >= titleLength){
        index=_index
        return pre
    }
    charCode = cur.charCodeAt(0)
    if(charCode>=0 && charCode<=128){
        return pre+1
    }else{
        return pre+1
    }
},0)
if(index){
    this.navigateItem[key] = value.substring(0,index)
}

然而在这过程中会出现如下问题

由于reduce是不会中断循环,直到遍历结束才会停止,因此可能存在达到num=6后后面的字符的num也为6,因此根据index拿到的值为错误的

解决方岸:上锁

checkInput(val){
    let index = 0
    let charCode = -1
    let flag = true
    let selfValue = val.split('')
    slefValue.reduce(pre,cur,_index) =>{
        if(pre>=4 && flag){
            index = _index
            this.input = val.substring(0,index)
            flag = true
            return pre
        }
        charCode = cur.charCodeAt(0)
        if(charCode>=0 && charCode<=128){ return pre+1 }
        else { return pre+2}
    },0)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值