This short tutorial describes how to correctly force a Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
To force Vue to rerender a component we have to change the key
attribute’s value to trigger the reloading of the component.
Let’s understand the concept with an example.
Rerender a component in Vue
There is no direct function in Vue to remount the component. Instead, we need to use the Vue key
property to change in a component so that a remount is triggered by Vue for that component. This is the same key
property which we specify in things like v-for
and is actually used to uniquely identify an element (or component) in the Vue template. When we do this, all the properties and methods for that component will be reinitialized or remounted.
Let’s say, in our Vue app we want to force rerender of a component ItemsList.vue
In parent component
<template>
<ItemsList />
</template>
Firstly, we need to bind the key property of the component and initialize it to a random value. For best performance and ease of use, we can initialize the key to an integer like 1 (Make sure 1 isn’t already assigned as key to any other element in the parent component).
In this example we call the variable ‘key’, but it can be any valid variable name.
<template>
<Itemslist :key="key" />
</template>
<script>
export default {
data() {
return {
key: 1
}
}
}
</script>
Next, we can have a button that can be clicked to call the function which triggers the reload.
<template>
<button @click="triggerRemount">Remount ItemsList</button>
<Itemslist :key="key" />
</template>
Create the function like so –
triggerRemount() {
this.key = this.key * (-1)
}
This will essentially create a toggle for the key with its value being either 1 or -1.
So, when we click on the button, the component ItemsList.vue
will be remounted i.e. everything inside it will be reinitialized. This way we can force the mounted hook in the component to be called again.
Why exactly does changing the key remount the component?
Vue is a reactive framework and when we change a component’s state, the whole DOM is not remounted and only the part where the change has happened is rerendered. To do this, sometimes Vue needs to assign unique identifiers or ‘keys’ to DOM Elements so that it can keep track of its state and on change, render them independently.
This is what exactly happens when we change the key property of the component. The component is uniquely identified by the key. When we change the key, Vue thinks that it is a different component now and as such renders it again.
Related Topics:
How to register a Global component in Vue 3 and Vue 2