element input,一个中文占3个字符

该代码示例展示了在Vue.js中如何限制el-input组件的输入长度,并在超出限制时自动截取字符串。通过计算每个字符的长度(中文字符计3,其他字符计1),确保不超过设定的最大长度。handleInput方法用于处理输入,assistTextLength方法用于辅助计算字符串长度。

思路:标记字符的下标,截取,重新赋值

在这里插入图片描述

代码如下,可直接复制预览

<template>
  <div class="form-item">
    <el-input
      v-model="testValue"
      :maxlength="maxlength"
      @input="handleInput"
    >
    </el-input>
    <span class="showMax">{{useLength}}/{{maxlength}}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      testValue: '',
      maxlength: 50,
      useLength: 0
    };
  },
  methods: {
    handleInput(val) {
      const { inputLen, arrayLen } = this.assistTextLength(val);
      console.log({ inputLen, arrayLen });
      if (inputLen > this.maxlength) {
        // 合适的位置截断
        let endIdx = 0;
        let sumLen = 0;
        for (let i = 0; i < arrayLen.length; i += 1) {
          if (sumLen < this.maxlength) {
            sumLen += arrayLen[i];
            i === arrayLen.length - 1 ? endIdx = i + 1 : '';
          } else {
            endIdx = i;
            break;
          }
        }
        this.$nextTick(() => {
          this.testValue = val.substring(0, endIdx);
          this.useLength = this.maxlength;
        });
      } else {
        this.useLength = inputLen;
      }
    },
    assistTextLength(value) {
      value = String(value);
      const arrayValue = value.split('');
      const reg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g; // 匹配中文和中文字符
      const arrayLen = [];
      arrayValue.forEach((v) => {
        const len = v.search(reg) > -1 ? 3 : 1;
        arrayLen.push(len);
      });
      let inputLen = 0;
      if (arrayLen.length > 0) {
        inputLen = arrayLen?.reduce((a, b) => a + b) || 0;
      }
      return {
        inputLen,
        arrayLen
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.form-item {
  position: relative;
}
.showMax {
  position: absolute;
  right: 0;
  bottom: -15px;
  font-size: 12px;
}
</style>

—end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值