In Vue 2, instance method this.$forceUpdate()
could be used to update the component manually. How can we force update component in Vue 3 - Composition API (inside setup method) ?
setup(props, context) {
const doSomething = () => {
/* how to call $forceUpdate here? */
}
return {
doSomething
}
}
Thanks, in advance.
Vue 3 does not require using the Composition API.
Better way: You can use forceUpdate Normally, Vue will react to changes in dependencies by updating the view. However, when you call forceUpdate , you can force that update to occur, even if none of the dependencies has actually changed.
Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It is an umbrella term that covers the following APIs: Reactivity API, e.g. ref() and reactive() , that allows us to directly create reactive state, computed state, and watchers.
You must install @vue/composition-api as a plugin via Vue. use() before you can use the Composition API to compose your component. 💡 When you migrate to Vue 3, just replacing @vue/composition-api to vue and your code should just work.
When I need to force an update in vue I usually add a key with a value I can change, which will then force vue to update it. That should work in vue 3 as well, though I admit I haven't ever tried it. Here's an example:
<template>
<ComponentToUpdate
:key="updateKey"
/>
</template>
<script>
export default {
data() {
return {
updateKey: 0,
};
},
methods: {
forceUpdate() {
this.updateKey += 1;
}
}
}
</script>
You can read more about it here: https://michaelnthiessen.com/key-changing-technique/
$forceUpdate
is still available in Vue3, but you won't have access to it in the setup()
function. If you absolutely need to use it, you can use object API component or this fancy trick...
app.component("my-component", {
template: `...`,
methods: {
forceUpdate(){
this.$forceUpdate()
}
},
setup(props) {
const instance = Vue.getCurrentInstance();
Vue.onBeforeMount(()=>{
// instance.ctx is not populated immediately
instance.ctx.forceUpdate();
})
return {doSomething};
},
})
If this seems like a ridiculous solution, trust your Judgement. Ideally your application would not rely on forceUpdate
. If you are relying on it, it likely means that something is miss-configured, and that should be the first thing to resolve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With