首页 > 解决方案 > Vue 3 中的 this.$forceUpdate 等效项 - 组合 API?

问题描述

this.$forceUpdate()在 Vue 2 中,可以使用实例方法手动更新组件。我们如何在 Vue 3 - Composition API(内部设置方法)中强制更新组件?

setup(props, context) {
   const doSomething = () => {
     /* how to call $forceUpdate here? */
   }

   return {
       doSomething
   }
}

提前致谢。

标签: vue.jsvue-componentvuejs3vue-composition-api

解决方案


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


推荐阅读