为什么 'this.count++' 和 Vue3 中的 'count.value++' 一样?
Why does 'this.count++' work the same as 'count.value++' in Vue3?
以下两个代码片段都使用 Vue3 组合正确地增加了计数器 API。我希望方法 1 可以通过做
count.value++
。但是为什么带有 this.count++
的方法 2 有效呢?有没有我们想要使用方法 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>
永远不要在 setup()
中使用 this
!
https://v3.vuejs.org/guide/composition-api-setup.html#usage-of-this
我假设它的工作原理是 setup()
就像一个构造函数,而你使用的是 function
而不是箭头函数,因此 this
可能指向 setup()
函数,count
是其中的一部分。
以下两个代码片段都使用 Vue3 组合正确地增加了计数器 API。我希望方法 1 可以通过做
count.value++
。但是为什么带有 this.count++
的方法 2 有效呢?有没有我们想要使用方法 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>
永远不要在 setup()
中使用 this
!
https://v3.vuejs.org/guide/composition-api-setup.html#usage-of-this
我假设它的工作原理是 setup()
就像一个构造函数,而你使用的是 function
而不是箭头函数,因此 this
可能指向 setup()
函数,count
是其中的一部分。