思路:标记字符的下标,截取,重新赋值
代码如下,可直接复制预览
<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