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="輸入手機(jī)號(hào)" 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>
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="輸入手機(jī)號(hào)"
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 asself.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, '')
}
}
})