Javascript is required
·
1 min read

Vue Tip: Best Way to Force Re-Render Vue Component

Vue Tip: Best Way to Force Re-Render Vue Component Image

If you read this article, you're most likely experiencing issues with Vue's reactivity system. In my experience, you're probably doing something wrong and not using Vue's reactivity system correctly.

However, there are scenarios where it's necessary to force the re-rendering of a component. An example of this is when you're using a third-party library that doesn't play well with Vue's reactivity system. If the third-party library directly modifies the DOM and doesn't provide a way to notify Vue of changes, you'll have to force the re-rendering of the component.

Let me show you the correct way to force re-render a Vue component using the key attribute:

App.vue
1<script setup>
2import { ref } from 'vue';
3
4const componentKey = ref(0);
5
6const forceRender = () => {
7  componentKey.value += 1;
8};
9</script>
10
11
12<template>
13  <MyComponent :key="componentKey" />
14  <button @click="forceRender">Force re-render</button>
15</template>

Each invocation of forceRender changes the componentKey value, which is added as key attribute to MyComponent. Vue recognizes this change, destroys the old component instance, and creates a new one.

Info

Check the official documentation for more information about the key attribute.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.