3
votes

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.

3

3 Answers

5
votes

$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.

2
votes

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/

1
votes
<script>
import {getCurrentInstance, defineComponent} from 'vue'
export default defineComponent({
  setup() {
    const instance = getCurrentInstance();
    instance.proxy.$forceUpdate();
  }
})
</script>

In TypeScript it'll be instance?.proxy?.$forceUpdate()