Force Vue to Re-Render Correctly

If you find yourself needing to force Vue to re-render a component, chances are the reactivity in your app is broken somewhere.

But, if you have a valid use case, forceUpdate is not working, or you simply need to get things working quickly, the best way to do this is through the Key Changing Technique:

<template>
<MyComponent :key="componentKey" />
</template>
<script setup>
import { ref } from 'vue';
const componentKey = ref(0);
const changeKey = () => {
componentKey.value += 1;
};
</script>

Here’s how you’d do it with the Options API if you’re not using Vue 3 or not using the Composition API:

export default {
data() {
return {
componentKey: 0,
};
},
methods: {
changeKey() {
this.componentKey += 1;
}
}
}

Using the key attribute lets us give Vue more information so it can correctly remove and replace DOM elements on the page. Because of the reactivity system, Vue can get confused about which elements need to be replaced in the DOM and which need to stay.

When we change the value of our key, Vue knows that this is a “new” component. It will destroy the existing component and then create and mount an entirely new one.

Problem solved!

But before you reach for this solution, make sure that there isn’t a reactivity issue in your application. This should only be used as a last resort, and is not a recommended approach.