search

Home  >  Q&A  >  body text

javascript - vue mobile terminal input numeric input optimization

This is used by the mobile terminal.
When the input type is number, there is no limit in English or Chinese, and maxlength does not work.
When the input type is tel, there is no limit in English or Chinese, but maxlength does. Function, so use tel,
keyup is to filter characters other than numbers.
May I ask if there is any room for optimization in this code?

<input v-model="phoneNumber" placeholder="输入手机号" type="tel" maxlength="11" @keyup="handleFilterLetters">

<script type="text/javascript">
    vm = new Vue({
            el: "#app",
            data: {
                phoneNumber: null,
            },
            methods: {
                handleFilterLetters: function(){
                    var self = this;
                    self.phoneNumber=self.phoneNumber.replace(/[^\d]/g,'');
                },
            }
        })
</script>
phpcn_u1582phpcn_u15822732 days ago1022

reply all(3)I'll reply

  • 迷茫

    迷茫2017-07-05 11:01:49

      The initial value of
    1. phoneNumber should be a string '', otherwise it is unsafe to call replace on a variable that may be null.

    2. var self = this is unnecessary.

    3. handleFilterLetters is so long, change it to onKeyUp to make it easier to read (

    4. <input> One line is too long, eslint-airbnb’s rule is

    <input
      v-model="phoneNumber"
      placeholder="输入手机号"
      type="tel"
      maxlength="11"
      @keyup="handleFilterLetters"
    />

    reply
    0
  • 怪我咯

    怪我咯2017-07-05 11:01:49

    Everything said above is correct
    The questioner can also pay more attention to the code style
    For example:
    self.phoneNumber=self.phoneNumber.replace(/[^d]/g,'');

    Write as
    self.phoneNumber = self.phoneNumber.replace(/[^d]/g,'');

    Better

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-07-05 11:01:49

    The local filter used here

    If you want a higher degree of reusability, global filter can also be used

    <p id="app" >
      <input :value="phone | num"  @keyup="phoneChange" />
    </p>
    var app = new Vue({
      el: "#app",
      data: { phone: "" },
    
      methods: {
        phoneChange(e) {
          this.phone = e.target.value
          this.$forceUpdate()  // 这里必须有
        }
      },
    
      filters: {
        'num': function(value) {
          return value.replace(/[^\d]/g, '')
        }
      }
    })

    reply
    0
  • Cancelreply