主要思路:
监听事件,每次号码发生改变时触发
大体的逻辑是:先比较号码变化前后的长度,判断是输入还是删除,如果是输入的话,利用正则表达式改变号码格式。
废话不多,上代码:
html:
<input
type="tel"
class="MobilePhone-user"
placeholder="请输入手机号"
v-model="phone"
/>
vue侦听器代码:
watch: {
phone(newValue) {
if(newValue.length>=13){
this.phone = this.phone.slice(0, 13);
// return
}
newValue = newValue.replace(/\s+/g, "");
if (newValue.length > 3 && newValue.length < 8) {
newValue = newValue.replace(/^(\d{3})/g, "$1 ");
} else if (newValue.length >= 8 && newValue.length < 12) {
newValue = newValue.replace(/^(\d{3})(\d{4})/g, "$1 $2 ");
}
this.phone = newValue;
return newValue;
},
},
当我们使用手机号时需要去除空格:
let str = this.phone.replace(/\s+/g, "");
console.log(str)