首页 > 解决方案 > 为什么 'this.count++' 与 Vue3 中的 'count.value++' 工作方式相同?

问题描述

以下两个代码片段都使用 Vue3 组合 API 正确地递增计数器。我希望方法 1 通过做 count.value++. 但是为什么方法 2this.count++有效呢?有没有我们想要使用方法 2 的情况?


方法一:

<template>
  <button @click="inc">{{ count }}</button>
</template>

<script>
import { ref } from "vue";
export default {
  setup() {
    const count = ref(0);
    const inc = function () {
      count.value++;
    };

    return {
      inc,
      count,
    };
  },
};

方法二:

<template>
  <button @click="inc">{{ count }}</button>
</template>

<script>
import { ref } from "vue";
export default {
  setup() {
    const count = ref(0);
    const inc = function () {
      this.count++;
    };

    return {
      inc,
      count,
    };
  },
};
</script>

标签: vue.jsvuejs3

解决方案


永远不要我们thissetup()

https://v3.vuejs.org/guide/composition-api-setup.html#usage-of-this

我假设它setup()像构造函数一样工作,并且您使用的是 afunction而不是箭头函数,因此this可能指向该setup()函数并且count是它的一部分。


推荐阅读