vue.js - 为什么 '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>
解决方案
永远不要我们this
!setup()
https://v3.vuejs.org/guide/composition-api-setup.html#usage-of-this
我假设它setup()
像构造函数一样工作,并且您使用的是 afunction
而不是箭头函数,因此this
可能指向该setup()
函数并且count
是它的一部分。
推荐阅读
- jquery - 如何在第二次点击时反转css动画
- highcharts - Highcharts 添加按钮修复图表
- ios - 在 Flutter iOS 上更改显示名称
- javascript - 仅在输入数据后刷新 html 页面
- assembly - 回显码:从打印变为返回
- ruby-on-rails - 如何高效地获取所有“拥有”特定记录的记录
- javascript - 如果选择子节点,则更新父节点 - 从子节点到父节点的树遍历
- xslt - 当使用 XSLT 满足条件时,如何显示某些文本?
- docker-compose - 如何在运行 docker 容器时修复错误
- core-data - 使用 SwiftUI 和 CoreData 的数据