I have to mention this before we go on. As the doc-Forcing-an-Update says:
If you find yourself needing to force an update in Vue, in 99.99% of cases, you’ve made a mistake somewhere.
When I come back to write a blog, I find it’s totally true. Well, let’s begin. Here is the demo code based on element-ui@2.4.11 and vue@2.5.17:
<div id="app"> |
Auto Update with Vue’s Reactivity System
Go check the doc.
$forceUpdate
For example, if someone made a mistake and wrote the code like
let length = app.items.length; |
You will not see the data update because you just add an nonreactive attribute. In this case, you might need app.$forceUpdate()
. However, better idea is using code like:
let length = app.items.length; |
or
let length = app.items.length; |
Reassign
However, it’s common to use third party components. In this case, it may not be easy to modify the component if we find something not good. For example, if we sort the data using:
app.items.reverse(); |
Here is the result:
The part above the hr
works as expected while the el-tree
doesn’t change even you use $forceUpdate
. So, in this case, what can we do?
We can make it update by reassigning like:
app.items = app.items.slice(); |
Until now, every thing about force update has been solved. I haven’t met problems which can’t be solved by ways above. However, there is some way stronger I have to mention.
v-if/key
In some cases, we do need to destroy and rebuild the component. But I didn’t find any API about rebuild
except this issue. Some guys said we can rebuild using v-if="isElTreeShow"
:
app.isElTreeShow = !app.isElTreeShow; |
or a better idea use :key="elTreeVersion"
app.elTreeVersion++; |
See? That’s pretty cool.