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>
The initial value of
phoneNumber
should be a string''
, otherwise it is unsafe to callreplace
on a variable that may be null.var self = this
is unnecessary.handleFilterLetters
is so long, change it toonKeyUp
to make it easier to read (<input>
One line is too long, eslint-airbnb’s rule isEverything 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