<input v-model.number="age" type="number">
look: https://codeshelper.com/a/11...
controls input can only enter numbers
< input type=" number "> can only enter numbers on both pc and mobile phones, but there is no completion or search button in the soft keyboard that pops up on the phone. After searching, the search button is not supported in the case of HTML5 number, and type='text' does have it. So the curve saves the nation, and the control form can only enter numbers. The original idea of
is to put it in
first
<input type='text' @input="handleInput" :value="val"/>
handleInput(e){
this.val=e.target.value.replace(/[^\d]/g,'');
}
but this does not refresh the form's data in real time, so the following will work
e.target.value=e.target.value.replace(/[^\d]/g,'');
write elegant points with custom instructions:
//<input type="text" v-number-only />
directives: {
numberOnly: {
bind: function(el) {
el.handler = function() {
el.value = el.value.replace(/\D+/, '')
}
el.addEventListener('input', el.handler)
},
unbind: function(el) {
el.removeEventListener('input', el.handler)
}
}
}
<div id="demo">
<input
type="text"
placeholder=""
@input="change"
@change="change"
:value="inpNum"
/>
</div>
new Vue({
el:'-sharpdemo',
data: {
oldNum: ''
},
computed: {
inpNum () {
return this.oldNum
}
},
methods: {
change (event) {
let val = event.target.value.trim()
// ,
if (/^[1-9]\d*$|^$/.test(val)) {
this.oldNum = val
} else {
event.target.value = this.oldNum
}
}
}
})
https://jsfiddle.net/BarryZha...
if it is on mobile, you can do this:
<input type="text" pattern="[0-9]*">
//<input v-model="num" v-number-only />
Vue.directive('numberOnly', {
bind: function () {
this.handler = function () {
this.el.value = this.el.value.replace(/\D+/, '')
}.bind(this)
this.el.addEventListener('input', this.handler)
},
unbind: function () {
this.el.removeEventListener('input', this.handler)
}
})
encapsulates a vue input box with limited numbers, adding verification, and can be used directly if necessary.
link
realization idea: do not use v-model, and then monitor the change of the value yourself, and judge the value in the monitoring event.
reference: http://jsbin.com/nabafidapu/1...
isn't computed recommended?
https://github.com/shiwanjun1994/vue-basic/tree/master/%E5%B8%B8%E7%94%A8%E7%BB%84%E4%BB%B6%E5%B0%81%E8%A3%85/components/CustomInput