先看代码,复制使用即可。这是一个比较常用的场景,汉字视为2个字符,字母和数字等视为一个字符,繁体汉字视为三个字符。
如您满意请给莫成尘点个star
这是一个具名函数
function getByteLength(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
当然也可以改为箭头函数并搭配elementui使用
(如果您单独使用需要您自己抽离代码)使用MessageBox 弹框组件
this.$prompt('这是标题', {
confirmButtonText: '确定',
cancelButtonText: '取消',
inputPlaceholder: '输入不大于10个字符',//input框的提示
inputErrorMessage: '字符数量错误或超出限制',//大于10个字符警告
inputValidator: (value) => {
let len = 0
for (let i = 0; i < value.length; i++) {
if (value.charCodeAt(i) > 127 || value.charCodeAt(i) == 94) {
len += 2
} else {
len++
}
}
if (len > 10) {
return '字符数量错误或超出限制'
} else if (/\s/.test(value)) { //不允许输入空格
return '标题中不允许出现空格'
}
return true
}
}).then(({ value }) => {
if (value) { //处理value 就是您输入的值
} else { //实际没什么用
this.$notify({
title: '失败',
message: '请输入名称',
type: 'error'
})
}
}).catch(() => { //取消操作触发的事件
this.$message({
type: 'info',
message: '取消输入'
})
})