javascript - vue mobile terminal input numeric input optimization
phpcn_u1582
phpcn_u1582 2017-07-05 10:59:49
0
3
975

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_u1582
phpcn_u1582

reply all(3)
迷茫
    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"
/>
刘奇

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

仅有的幸福

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, '')
    }
  }
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!