Forcing a Component to Update

What do you do if a component isn’t updating the way it should?

Likely, this is caused by a misunderstanding and misuse of the reactivity system.

But let’s look at a quick solution using forceUpdate:

import { getCurrentInstance } from 'vue';
const methodThatForcesUpdate = () => {
// ...
const instance = getCurrentInstance();
instance.proxy.forceUpdate();
// ...
};

Using the Options API instead:

export default {
methods: {
methodThatForcesUpdate() {
// ...
this.$forceUpdate(); // Notice we have to use a $ here
// ...
}
}
}

Now, here comes the sledgehammer if the previous approach doesn’t work.

I do not recommend using this approach. However, sometimes you just need to get your code to work so you can ship and move on.

But please, if you do this, keep in mind this is almost always the wrong way, and you’re adding tech debt in to your project.

We can update a componentKey in order to force Vue to destroy and re-render a component:

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

The process is similar with the Options API:

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

You can find a deeper explanation here: https://michaelnthiessen.com/force-re-render/