当前位置: 首页 > Web前端 > vue.js

Vue组件---输入字数限制

时间:2023-03-31 22:39:03 vue.js

Vue.component('input-len-control',{template:`{{curLen}}/{{maxLen}}

`,data(){return{curLen:0,//当前输入值的长度input:''}},//父子组件双向绑定model:{prop:'inputValue',event:'change'},props:{maxLen:{type:Number,default:16},placeholder:String,inputValue:{type:String,default:''}},watch:{//使用默认值初始化inputValue:{handler(val){const{returnStr,len}=getTagLen(val,this.maxLen)this.curLen=lenthis.input=returnStr},immediate:true}},mounted(){},方法:{inputControl(val){const{returnStr,len}=getTagLen(val)this.curLen=lenthis.input=returnStrthis.$emit('改变',returnStr)}}})functiongetTagLen(str,maxLen){letreg=/^[\u4e00-\u9fa5]{0,}$/;让len=0;让returnStr="";如果(str===""){return{returnStr,len}}str=str.split('');for(leti=0;i=maxLen-1)中断;长度+=2;}else{len++;}returnStr+=str[i];如果(len>=maxLen)中断;}return{returnStr,len}}基本样式.input-control-wrapper{position:relative;高度:32px;}.input-control-wrapper输入[类型="文本"]{框大小调整:边框框;宽度:100%;高度:32px;边框:1px实心#ccc;行高:32px;左填充:6px;填充右:35px;颜色:#333;}.input-control-wrapper.control{位置:绝对;宽度:35px;行高:32px;字体大小:12px;颜色:#999999;右:0;顶部:0;文本对齐:居中;}