In some situations, you might end up having to re-render components by yourself. Hopefully, you won't have to use it too often, but in the case that you are, at least know that you are doing it the best way.
So what is the best way?
The answer is setting a :key on the component you want to re-render. When we want to re-render it, we just increment the key. Brilliant isn't it.
Vue uses the key in order to identify VNodes when it compares the new list of nodes with the previous list of nodes. Vue will know how to order them, add new, or destroy elements when elements with certain keys are no longer present.
Vue also has an algorithm that will minimize component re-render to save performance when the key is not present, but nonetheless, try to provide your own unique keys when looping through data.
A simple usage would look like:
<template>
<special-component :key="specialComponentKey"></special-component>
</template>
<script>export default {
data() {
return {
specialComponentKey: 0
}
},
methods: {
reRenderComponent() {
this.specialComponentKey++;
}
}
}
</script>
Every time we need to re-render our specialComponent we would call a reRenderComponent method which increments the key and because the key changed, the component will be re-rendered.