输入框绑定
<input class="inputBox" type="phone" placeholder=" 请输入手机号" maxlength="13" v-model="phoneNum"/>
监听事件,每次号码发生改变时触发
大体的逻辑是:先比较号码变化前后的长度,判断是输入还是删除,如果是输入的话,利用正则表达式改变号码格式。
watch: {
phoneNum (newValue, oldValue) { // 监听电话号码
this.phoneNum = newValue.length > oldValue.length ? newValue.replace(/\s/g, '').replace(/(\d{3})(\d{0,4})(\d{0,4})/, '$1 $2 $3') : this.phoneNum.trim()
if (this.phoneNum.length === 13) {
// 验证/保存的手机号码,去除空格
this.state.checkPhoneNum = this.phoneNum.replace(/\s/g, '')
console.log('输入的电话号码是:', this.state.checkPhoneNum)
}
}
},
效果示意