this.$forceUpdate 在 Vue 3 中等效 - Composition API?

新手上路,请多包涵

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

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

   return {
       doSomething
   }
}

提前致谢。

原文由 saibbyweb 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3.6k
2 个回答

$forceUpdate 在 Vue3 中仍然可用,但您将无法在 setup() 函数中访问它。如果你绝对需要使用它,你可以使用对象 API 组件或这个花哨的技巧……

 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};
  },
})

如果这看起来像是一个荒谬的解决方案,请相信您的判断力。理想情况下,您的应用程序不会依赖 forceUpdate 。如果您依赖它,则 可能 意味着配置错误,这应该是首先要解决的问题。

原文由 Daniel 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果使用选项 API:

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

如果将 Composition API 与