Look at the code first, just copy and use it. This is a more commonly used scenario. Chinese characters are treated as two characters, letters and numbers are treated as one character, and traditional Chinese characters are treated as three characters.
If you are satisfied, please give Mo Chengchen a star
This is a named function
functiongetByteLength(str =''){
let len =0;for(let i =0; i < str.length; i++){
if(str.charCodeAt(i)>127|| str.charCodeAt(i)==94){
len +=2;}else{
len++;}}return len;}
console.log(getByteLength('汉字汉字123'))//11
Of course, it can also be changed to an arrow function and used with elementui
(如果您单独使用需要您自己抽离代码)使用MessageBox 弹框组件
this.$prompt('这是标题',{
confirmButtonText:'确定',
cancelButtonText:'取消',
inputPlaceholder:'输入不大于10个字符',//input框的提示
inputErrorMessage:'字符数量错误或超出限制',//大于10个字符警告
inputValidator:(value)=>{
let len =0for(let i =0; i < value.length; i++){
if(value.charCodeAt(i)>127|| value.charCodeAt(i)==94){
len +=2}else{
len++}}if(len >10){
return'字符数量错误或超出限制'}elseif(/\s/.test(value)){
//不允许输入空格return'标题中不允许出现空格'}returntrue}}).then(({
value })=>{
if(value){
//处理value 就是您输入的值}else{
//实际没什么用this.$notify({
title:'失败',
message:'请输入名称',
type:'error'})}}).catch(()=>{
//取消操作触发的事件this.$message({
type:'info',
message:'取消输入'})})