1 min read499 views
Vue Tip: Best Way to Force Re-Render Vue Component
In certain scenarios, Vue's reactivity approach isn’t sufficient, and we need to force re-rendering of specific components.
Ask my AI assistant
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:
<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.
key attribute.