-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Serval Ways to Force Update in Vue #47
Comments
I have to mention this before we go on. As the doc-Forcing-an-Update says:
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">
<p v-for="item in items" :key="item.id">{{ item.label }}</p>
<hr />
<el-tree
:data="items"
show-checkbox
node-key="id"
:default-expanded-keys="[2, 3]"
v-if="isElTreeShow"
:key="elTreeVersion"
>
</el-tree>
</div>
<script>
window.app = new Vue({
el: '#app',
data: {
isElTreeShow: true,
elTreeVersion: 100,
items: [
{
id: 1,
label: 'Level one 1'
},
{
id: 2,
label: 'Level one 2',
children: [
{
id: 21,
label: 'Level two 2-1'
}
]
},
{
id: 3,
label: 'Level one 3'
}
],
compare(a, b) {
return a.id - b.id
},
compareReverse(a, b) {
return -this.compare(a, b)
}
}
})
</script> Auto Update with Vue's Reactivity SystemGo check the doc. $forceUpdateFor example, if someone made a mistake and wrote the code like let length = app.items.length
app.items[length] = { id: length + 1, label: `Level one ${length + 1}` } You will not see the data update because you just add an nonreactive attribute. In this case, you might need let length = app.items.length
app.items.push({ id: length + 1, label: `Level one ${length + 1}` }) or let length = app.items.length
this.$set(app.items, length, {
id: length + 1,
label: `Level one ${length + 1}`
}) ReassignHowever, 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 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/keyIn some cases, we do need to destroy and rebuild the component. But I didn't find any API about app.isElTreeShow = !app.isElTreeShow
app.$nextTick(() => {
app.isElTreeShow = !app.isElTreeShow
}) or a better idea use app.elTreeVersion++ See? That's pretty cool. |
vuejs/Discussion#356
when you want to totally re-render the component, use key instead of $forceUpdate. Sometimes, it can solve the problem which $forceUpdate can't solve.
The text was updated successfully, but these errors were encountered: