Vue实现数字输入框中分割手机号码的示例

时间:2019-04-07
本文章向大家介绍Vue实现数字输入框中分割手机号码的示例,主要包括Vue实现数字输入框中分割手机号码的示例使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

需求

在移动端弹出系统数字键盘,输入手机号码的时候,使用344形式分割。

分析:

  1. 首先,如果要在移动端弹出数字键盘,并且还可以有空格,那么就要使用type="phone"的input框
  2. 如果要实现输入的时候增加空格,删除的时候减少空格,那么就要使用watch
  3. 手机号码为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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。