My html code like this :
<div id="app">
<input type="number" v-model="quantity"/>
</div>
My vue component like this :
new Vue({
el: '#app',
data: {
quantity: ''
},
watch: {
quantity (val) {
this.quantity = val.replace('.', '')
}
}
})
Demo and full code like this : https://jsfiddle.net/50wL7mdz/67375/
For example
I input 10.2
, it will automatic to be 102
If I input 10..2
, it not automatic to be 102
So if multiple dot, it does not work
How can I solve this problem?
Because you are using type="number"
, the browser is doing some internal processing, so the value
of the input (which is bound to your variable) is a Number, and is not exactly the same as the text in the box.
In particular, if the text in the box is not a valid number, the internal value is empty. When you type one '.', the value doesn't change: 10.
and 10
are the same numeric value. When you type the 2nd '.', the value becomes invalid, so the internal value is empty. Somewhat confusingly, what you typed in the input stays visible, but there is no way to get at it.
Your options are to stop using type="number"
in which case your code will work as written (but you don't have the up- and down-arrow functionality for changing the value), or to do something tricky.
Update: The solution below works relatively nicely by forcing a canonicalized version of the number to be used. The caveat is that your cursor will be moved to the end of the number each time you make a change. You can address that, but it's somewhat complicated so I didn't do it here.
new Vue({
el: '#app',
data: {
quantity: ''
},
computed: {
ppQuantity: {
get() {
return this.quantity;
},
set(val) {
this.quantity = '';
this.$nextTick(() => {
this.quantity = val.replace('.', '');
});
}
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<input type="number" v-model="ppQuantity">
</div>