【问题标题】:this.$forceUpdate equivalent in Vue 3 - Composition API?Vue 3 中的 this.$forceUpdate 等效项 - 组合 API?
【发布时间】:2021-07-31 18:59:30
【问题描述】:

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

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

   return {
       doSomething
   }
}

谢谢,提前。

【问题讨论】:

    标签: vue.js vue-component vuejs3 vue-composition-api


    【解决方案1】:

    $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。如果您依赖它,可能意味着某些配置错误,这应该是首先要解决的问题。

    【讨论】:

    • 我知道forceUpdate 应该尽一切可能避免,只是好奇它是如何在setup() 中完成的。一周前刚迁移到 Vue 3,在任何地方的文档中都找不到它。谢谢。
    • Property 'ctx' does not exist on type 'ComponentInternalInstance' 在 Vue 3.2 中。看起来它在这个提交中被重命名为proxygithub.com/vuejs/vue-next/commit/…。请参阅下面的答案。
    • 我用 vue 3.2.0 测试过,它仍然可以工作
    • 如果您查看提交,ctx 在那里,但是也正在添加 ctx (proxy) 的代理。在某些情况下,可能需要代理来进行反应,但情况似乎并非如此。我没有看到任何提到在release changelog 中删除ctx,这样的更改将保证vue 团队的更多沟通。
    【解决方案2】:

    当我需要在 vue 中强制更新时,我通常会添加一个可以更改值的键,然后强制 vue 更新它。这也应该在 vue 3 中工作,尽管我承认我从未尝试过。这是一个例子:

    <template>
      <ComponentToUpdate
        :key="updateKey"
      />
    </template>
    
    <script>
      export default {
        data() {
          return {
            updateKey: 0,
          };
        },
        methods: {
          forceUpdate() {
            this.updateKey += 1;
          }
        }
      }
    </script>
    

    您可以在此处阅读更多信息:https://michaelnthiessen.com/key-changing-technique/

    【讨论】:

    • 不错的技巧,谢谢。我正在为 vue2 使用 vue-composition-api,它工作得很好:)
    【解决方案3】:
    <script>
    import {getCurrentInstance, defineComponent} from 'vue'
    export default defineComponent({
      setup() {
        const instance = getCurrentInstance();
        instance.proxy.$forceUpdate();
      }
    })
    </script>
    

    在 TypeScript 中它将是 instance?.proxy?.$forceUpdate()

    【讨论】:

      猜你喜欢
      • 2022-11-05
      • 2022-11-24
      • 2021-06-18
      • 2021-06-02
      • 2021-07-12
      • 2020-12-20
      • 2023-04-02
      • 2022-07-19
      • 2020-12-20
      相关资源
      最近更新 更多