最终效果
实现
<template>
<div class="nearshopCharge">
<div class="main_form_pane">
<div class="form_item">
<label for="消费者手机号码">
消费者手机号码
<span class="red">*</span>
</label>
<div class="input_item">
<input class="text" maxlength="13" v-model="phone" placeholder="请填写用户的手机号码" type="tel" />
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "nearshopCharge",
data() {
return {
imgtop: require(`../../assets/public/Vue-assets/img/buy_song/pic55.png`),
num: 0,
selectXy: false,
name: "",
phone: "",
money: "",
inputKeyVal: ""
};
},
watch: {
phone(newValue, oldValue) {
//Remove Chinese
this.phone = this.phone.replace(/[\u4e00-\u9fa5]/g, "");
//Remove English
this.phone = this.phone.replace(/[A-Za-z]+$/g, "");
//Remove symbol
let reg = new RegExp(
"[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~!@#¥……&*()——|{}【】‘;:”“'。,、\\_\\+\\-\\%?]"
);
this.phone = this.phone.replace(reg, "");
// Remove blank
if (this.inputKeyVal == "Space") {
this.phone = oldValue
this.inputKeyVal = ''
}
// Delete or Input
if (newValue.split("").length < oldValue.split("").length) {
return false;
}
// Split numbers
let phoneStr = newValue.split("");
// Insert blank in 4 , 9 , 14
if (newValue.split("").length === 4) {
phoneStr.splice(3, 0, " ");
this.phone = phoneStr.join("");
} else if (newValue.split("").length === 9) {
phoneStr.splice(8, 0, " ");
this.phone = phoneStr.join("");
} else if (newValue.split("").length === 14) {
this.phone = oldValue.split("");
}
}
},
mounted() {
addEventListener("keydown", val => {
this.inputKeyVal = val.code;
});
}
};
</script>