Vue项目在表单中限制输入数字

<template>
  <div>
    <input
      v-model="userPhone"
      autofocus
      type="text"
      maxlength="11"
      placeholder="请输入11位手机号"
      @input="handlePhone"
      @keyup.enter="handleLogin"
    >
    <button type="button" @click="handleLogin">登录</button>
  </div>
</template>

JavaScript部分

<script>
export default {
  data () {
    return {
      userPhone: ''
    }
  },

  methods: {
    handlePhone (e) {
      this.userPhone = e.target.value.replace(/[^\d]/g, '')
    },

    handleLogin () {
      if (this.userPhone.length === 11) {
        console.log('登录成功')
      }
    }
  }
}
</script>

注意重点:表单的内容改变必须使用input事件来处理,必须随时监测表单输入的内容,不能使用watch和change,因为输入法在输入中文的时候监测不到,还要注意的就是表单input的type类型为number的时候移动端可以输入字母e,因为是科学计算法,还可以输入运算符(+,-,*,/)等等。

posted @ 2018-12-01 16:25  前端精髓  阅读(1887)  评论(0编辑  收藏  举报
在这里插入图片描述