Preface
When I was using form validate in Vue, I found sometimes vue doesn’t render data which was modified by me. I even thought it was a bug. Anyway, let’s take a look.
Main
Here is a simple demo:
html, |
<div class="app" id="app"> |
let app = new Vue({ |
When I was pressing dddddddddd, what did I got?
The first letter was replaced to 1 but the others not. And the most important is the result I got is always 1 which means this.positiveNum
is 1 while the value in the input
is not 1.
Why?
I even thought it was a bug until one day I met a similar problem which was solved in SO.
The key is the Lifecycle. The guide mentions it before but I didn’t understand it until now. Let’s see the picture again:
See?
The first time we change positiveNum
to 1 and then we always change positiveNum
to 1. So, vue wouldn’t re-render because the data doesn’t change. So, the connection between input
and positiveNum
was cut off until positiveNum
isn’t equal to 1.
We can add updated
to see how many times data has changed:
let app = new Vue({ |
As explained before, you can only see 'data updated'
once.
So, how can we solved this problem?
The key is still the Lifecycle. Vue wouldn’t re-render because data doesn’t change. So, we can update data after data has been changed and rendered. Understood? See code below:
<div class="app" id="app"> |
let app = new Vue({ |
See? I move the origin logic to the this.$nextTick(callback)
. Every time you press the wrong button, it will pass the wrong value to positiveNum
and will be corrected in this.$nextTick(callback)
which will make the logic run correctly. Also, you can see the updated log at the console.