【问题标题】:How to forceUpdate in setup in vue3?如何在 vue3 的设置中强制更新?
【发布时间】:2021-06-06 07:01:39
【问题描述】:

如何在 vue3 的 setup 中强制更新?

在使用Options Api时,我可以使用this.$forceUpdate()来强制更新。如何在vue3的setup函数中做同样的事情?

【问题讨论】:

  • 您能给我们举个例子,在这种情况下您需要 forceUpdate 吗?还有other ways to re-render a component
  • @wittgenstein 读起来很难,但我喜欢你在 Tractatus 上的工作。
  • 这是个好问题,我也在寻找答案

标签: vue.js vuejs3


【解决方案1】:

<script lang="ts">
import { defineComponent, getCurrentInstance } from "vue";

export default defineComponent({
  setup() {
    const { ctx: _this }: any = getCurrentInstance()
    let arr = [1]
    const handleClick = () => {
      arr.push(2)
      _this.$forceUpdate()
    }
    return {
      arr
    };
  },
});
</script>
<template>
  <div>
    <div>{{arr}}</div>
    <button @click="handleClick">add</button>
  </div>
</template>

完成

【讨论】:

  • 如果我们改为使用 const arr = ref([1], arr 将是反应性的,而 forceUpdate 将是不必要的。这就是 Vue 文档警告不要使用 getCurrentInstance 的原因 - 除非你正在做一些高级案例,这几乎总是一个错误。v3.vuejs.org/api/composition-api.html#getcurrentinstance
猜你喜欢
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 2021-09-03
  • 2011-10-31
  • 1970-01-01
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多