需求:在input框中输入手机号要求显示用空格分隔成 "xxx-xxxx-xxxx"的格式
解决方法:在 input 的上添加监听事件,如 onkeyup(原生input标签) 或 onchange(某些第三方组件),对输入的内容进行处理再显示出来。
笔者采用的是Elemrnt UI 的 input 组件,监听事件为input
<el-input
v-model="mobile"
placeholder="请输入手机号"
type="tel"
clearable
@input="validateMobile"
></el-input>
处理手机字符串的方法 如下:
validateMobile(val) {
let len=val.length;
let reg = new RegExp("\\s","g");
let mobile_ = "";
let mobile=val;
//去掉空格
mobile = mobile.replace(reg,"");
for(let i = 0;i < len;i++){
if(i == 2||i == 6)
{
mobile_ = mobile_ + mobile.charAt(i) + " ";
}
else
{
mobile_ = mobile_ + mobile.charAt(i);
}
}
this.mobile = mobile_;
}
同理可将手机号用其他分隔符,如“-”等,按照其他格式分隔。