·
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
<script setup> import { ref } from 'vue'; const componentKey = ref(0); const forceRender = () => { componentKey.value += 1; }; </script> <template> <MyComponent :key="componentKey" /> <button @click="forceRender">Force re-render</button> </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.