Home > Mobile >  Why does 'this.count ' work the same as 'count.value ' in Vue3?
Why does 'this.count ' work the same as 'count.value ' in Vue3?

Time:11-03

Both of the following code snippets increments the counter correctly using the Vue3 composition API. I expect method 1 to work by doing count.value . But why does method 2 with this.count work? Is there ever a situation where we would want to use method 2?


Method 1:

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

Method 2:

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

CodePudding user response:

Never us this in setup()!

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

I assume it works as setup() acts like a constructor and you are using a function and not an arrow function, thus this probably points to the setup() function and count is part of it.

  • Related