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>
迷茫2017-07-05 11:01:49
phoneNumber
should be a string ''
, otherwise it is unsafe to call replace
on a variable that may be null.
var self = this
is unnecessary.
handleFilterLetters
is so long, change it to onKeyUp
to make it easier to read (
<input>
One line is too long, eslint-airbnb’s rule is
<input
v-model="phoneNumber"
placeholder="输入手机号"
type="tel"
maxlength="11"
@keyup="handleFilterLetters"
/>
怪我咯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 asself.phoneNumber = self.phoneNumber.replace(/[^d]/g,'');
Better
仅有的幸福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, '')
}
}
})