需求:在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_;
}
同理可將手機號用其他分隔符,如“-”等,按照其他格式分隔。