Reputation: 16354
I am trying to build an only numeric field with VueJS. It kind of works but something is wrong:
You can try with this JSFiddle I made: https://jsfiddle.net/El_Matella/rr2qex8k/
Here is my text field component:
const TextField = {
template: '<div><input type="text" v-model="copy"></div>',
props: ['value'],
data () {
return {
copy: null
}
},
created () {
this.copy = this.value.toString()
},
watch: {
value () {
this.copy = this.value.toString()
},
copy () {
this.$emit('input', this.copy)
}
}
}
Here is the code that should allow me to use that text field component as an only numeric text:
new Vue({
el: '#app',
data: {
number: 1
},
methods: {
update (value) {
this.number = parseInt(value.replace(/\D/g, ''))
}
},
components: {
TextField
}
})
The problem is that the input field does not update when the last entered char is a non numeric value. You have to enter an other numeric value in order to update the input and remove the non numeric chars.
Upvotes: 0
Views: 6989
Reputation: 25221
You can use a getter and setter on a computed value to cleanse your input value on the way in:
const TextField = {
template: '<div><input type="text" v-model="inputValue"></div>',
props: ['value'],
data(){
return {
number: 0
}
},
computed: {
inputValue: {
get: function(){
return this.number;
},
set: function(value){
this.number = parseInt(value.replace(/\D/g, ''))
}
}
}
}
Upvotes: 0
Reputation: 571
try this on your input tag
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
or
<input type="number" />
you can check for compatibility here:
https://caniuse.com/#search=type%3D%22number%22
Upvotes: 4