vue 输入框中英文限制次数

以英文限制在10个,中文限制在五个为例

     <input ref="ipt"
        class="inputtext"
        v-model="item.name"
        @input="ChangeWith"
      />
methods:{
    //输入框字数限制
    ChangeWith() {
      let leng = this.validateTextLength(this.item.name);
      if (leng >= 5) {
        this.$refs.ipt.maxLength = leng;
      } else {
        this.$refs.ipt.maxLength = 10;
      }
    },
    validateTextLength(value) {
      // 中文、中文标点、全角字符按1长度,英文、英文符号、数字按0.5长度计算
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g;
      let mat = value.match(cnReg);
      let length;
      if (mat) {
        length = mat.length + (value.length - mat.length) * 0.5;
        return length;
      } else {
        return value.length * 0.5;
      }
    },
}

然后发现这个方法存在漏洞,就是单个只输入英文或者中文它的判断是对的,但是中英文混合就不行了,然后我加了改善,

    //输入框字数限制
    ChangeWidth: function() {
      let namelen = this.validateTextLength(this.item.name);
      if (namelen > 5) {
        let newnameindex = 0;
        let i = 0;
        let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
        for (i = 0; i < this.item.name.length; i++) {
          let mat = this.item.name[i].match(cnReg);
          newnameindex = newnameindex + (mat ? 1 : 0.5);
          if (newnameindex >= 5) {
            break;
          }
        }
        this.$refs.ipt.maxLength = i + 1;
        // this.item.name = this.item.name.substring(0,i + 1 );等同于上面的maxLength
      }
      this.item.width = this.textWidth(this.item.name) + 42;
      if (this.item.width < 65) {
        this.item.width = 65;
      }
    },
    validateTextLength(value) {
      // 中文、中文标点、全角字符按1长度,英文、英文符号、数字按0.5长度计算
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g;
      let mat = value.match(cnReg);
      let length;
      if (mat) {
        length = mat.length + (value.length - mat.length) * 0.5;
        return length;
      } else {
        return value.length * 0.5;
      }
    },

然后就完美了,中英文结合也没有毛病。