Reputation: 778
I have a text input that allow user to type a number with maximum of 3 digits after decimal point:
<v-text-field type="text" :value="num" @change="changeNum($event)" />
<p>{{ num }}</p>
...
export default {
data: () => ({
num: 0
}),
methods: {
changeNum(e) {
let v = parseFloat(e);
if (!isNaN(v)) {
this.num = parseFloat(v.toFixed(3));
}
}
}
};
If I type '123.456'
, then num = 123.456
.
If I append text '789'
, then input will contain 123.456789
but num = 123.456
. So, user may think that the changes have been applied, but it is not...
How can I force the input to update, if changeNum
fails?
Upvotes: 3
Views: 3304
Reputation: 1
You could achieve your use case by using only v-model.lazy
to change data after leaving the textfield, and watch
property which save the old and new value that allows us to control the typed value after focusing somewhere else.
new Vue({
el: '#app',
data: () => ({
num: 0
}),
watch: {
num(newv, oldv) {
let v = parseFloat(newv);
if (!isNaN(v)) {
this.num = parseFloat(v.toFixed(3));
} else {
this.num = oldv;
}
}
}
})
#app {
padding: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Vue.delete">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model.lazy="num" />
<p>out: {{ num }}</p>
</div>
</body>
Upvotes: 4
Reputation: 7187
I think that $forceUpdate
should solve your issue ..
methods: {
changeNum(e) {
let v = parseFloat(e);
if (!isNaN(v)) {
this.num = parseFloat(v.toFixed(3));
this.$forceUpdate();
}
}
}
Upvotes: 2
Reputation: 4714
@change
won't fire until you change focus to something else. To ensure you evaluate the input as you type, use @input
instead. It will fire with every keystroke.
Also, keep track of the last value so you can reset:
<v-text-field type="text" :value="num" @input="changeNum($event)" />
<p>{{ num }}</p>
...
export default {
data: () => ({
num: 0,
lastNum: 0
}),
methods: {
changeNum(e) {
let v = parseFloat(e);
if (!isNaN(v)) {
this.num = parseFloat(v.toFixed(3));
this.lastNum = this.num;
}
else {
this.num = this.lastNum;
}
}
}
};
Upvotes: 2