Sometimes we want to force a Vue.js component to reload or re-render a component.
In this article, we’ll look at how to force a Vue.js component to reload or re-render a component.
The forceUpdate Method
One way to force a component to re-render is to use the forceUpdate
method.
For instance, we can write:
<template>
<div id="app">
<button @click="forceUpdate">force update</button>
</div>
</template>
<script>
export default {
name: "App",
methods: {
forceUpdate() {
this.$forceUpdate();
},
},
};
</script>
to call the $forceUpdate
method in our component.
However, a re-rendering is done when we update any reactive property, so the better way to force re-rendering a component is to update reactive properties.
Changing the Component’s Key Prop
We can change the component’s key
prop to make the component re-render.
This is because a prop should be set to a reactive property as its value.
And reactive properties changes will make a component re-render.
For instance, we can write:
App.vue
<template>
<div id="app">
<HelloWorld :key="key" />
<button @click="forceUpdate">reload</button>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
key: 0,
};
},
methods: {
forceUpdate(name) {
this.key++;
},
},
};
</script>
components/HelloWorld.vue
<template>
<div class="hello">hello world</div>
</template>
<script>
export default {
name: "HelloWorld",
};
</script>
We have the HelloWorld
component with the key
prop that is set to the key
reactive property.
And we have the forceUpdate
method that’s called when we click the reload button.
The key
reactive property updates which will force everything in the App
component to re-render including the HelloWorld
component.
As long as the value of key
changes, re-rendering will be done.
Conclusion
We can force a re-render or reload of a component with the $forceUpdate
method or updating the key
prop of a component.