本篇文章主要介绍了Vue实现数字输入框中分割手机号码的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
需求
在移动端弹出系统数字键盘,输入手机号码的时候,使用344形式分割。
分析:
- 首先,如果要在移动端弹出数字键盘,并且还可以有空格,那么就要使用type="phone"的input框
- 如果要实现输入的时候增加空格,删除的时候减少空格,那么就要使用watch
- 手机号码为11位,加上两个空格,最多13位,因此要限定长度
代码实现
<body>
<div id="app">
<!-- 类型为phone,最大长度为13 -->
<input type="phone" v-model="dataPhone" maxlength="13">
</div>
</body>
<script>
var vm = new Vue({
el: '#app',
data() {
return {
dataPhone: ''
}
},
watch: {
// 通过watch来设置空格
dataPhone(newValue, oldValue) {
if (newValue.length > oldValue.length) { // 文本框中输入
if (newValue.length === 3 || newValue.length === 8) {
this.dataPhone += ' '
}
} else { // 文本框中删除
if (newValue.length === 9 || newValue.length === 4) {
this.dataPhone = this.dataPhone.trim()
}
}
}
}
})
</script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。 |