【发布时间】:2021-08-04 18:02:20
【问题描述】:
我很困惑...鉴于以下两个示例:
示例 1:https://jsfiddle.net/luckylooke/rbzwme91/
new Vue({
el: "#app",
data: {
message: "Hello!",
myPropInternal: 0,
},
computed: {
myProp: {
// getter
get: function () {
console.log('get', this.myPropInternal);
return this.myPropInternal;
},
// setter
set: function (value) {
console.log('set', value);
this.myPropInternal = value;
}
}
},
created: function() {
this.myProp = 1;
this.myProp = 2;
this.myProp = 3;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<h1>{{ message }} - {{ myProp }}</h1>
</div>
示例 2:https://jsfiddle.net/luckylooke/9khzv7a1/8/
const myObject = {
myPropInternal: 0,
get myProp() {
console.log('get', this.myPropInternal);
return this.myPropInternal;
},
set myProp(value) {
console.log('set', value);
this.myPropInternal = value;
}
};
new Vue({
el: "#app",
data: {
message: "Hello!",
myObject
},
created: function() {
this.myObject.myProp = 1;
this.myObject.myProp = 2;
this.myObject.myProp = 3;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<h1>{{ message }} - {{ myObject.myProp }}</h1>
</div>
示例 1 导致此控制台日志:
"set", 1
"set", 2
"set", 3
"get", 3
我希望模型的每次更改都会导致计算值(getter)进行评估,就像在示例 2 中一样,其中的输出是:
"get", 0
"get", 0
"set", 1
"get", 1
"set", 2
"get", 2
"set", 3
"get", 3
为什么 Vue 没有对第一个示例中的每个更改立即做出反应?
【问题讨论】:
-
计算被优化为不会被相同的值触发。
-
我得说我 100% 忘记了 computed setters 的存在。
-
@EstusFlask 我同意,但 1,2,3 不一样 ;)
-
iirc 这个是vue优化的,我会努力找源码的。
-
即使它是一种优化,它也会在错误的地方进行优化,因为第二个示例正在绕过它:/
标签: vue.js vue-reactivity