I am trying to build an only numeric field with VueJS. It kind of works but something is wrong:
- PASS: Enter 12 in the text field, the value in VueJS is 12, the visual is 12.
- FAILS: Enter 12a in the text field, the value in VueJS is 12, the visual is 12a. (expected behaviour is 12 in the text field)
- PASS: Enter 12a4 in the text field, the value in VueJS is 12a4, the visual is 124
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.