vuejs如何知道缓存的计算属性的依赖性? [英] How vuejs knows the depenedencies of computed property for caching?
问题描述
我有这个Vue.js代码:
I have this Vue.js code:
new Vue({
data:{
myValue:'x',
myOtherValue:'y'
},
computed: {
myComputed: myFunction(){
return this['my' + 'Value']
}
}
})
当你可以看到计算属性将被缓存,它只依赖于 data.myValue
。我的问题是Vue.js缓存系统如何知道只有在 myValue
被更改时再次运行计算函数?
As you can see the computed property will be cached and it is depended only on data.myValue
. My question is how Vue.js caching system knows that run the computed function again only if myValue
is changed?
如果我更改 myOtherValue
变量, myComputed
函数将使用缓存,并且不会再次运行我将调用它。
If I change the myOtherValue
variable, the myComputed
function will use the cache, and will not be run again will I call it.
我想到了几种可行的方法。但Vuejs如何做到这一点?
我读过这篇文章: https://vuejs.org/v2/guide/computed .html 并没有找到答案。
I thought about several ways how it is possible. But how Vuejs doing that? I have read this article: https://vuejs.org/v2/guide/computed.html and found no answer.
这段代码会发生什么,它将被依赖什么?
And what happen in this code, what it will be depeneded on?
const flag=2
new Vue({
data:{
myValue:'x',
myOtherValue:'y'
},
computed: {
myComputed: myFunction(){
if (flag==1){
return this['my' + 'Value']
}
else
return this['my' + 'Other' + 'Value']
}
}
})
奖金:我将会感谢我链接到VueJS代码中的相关功能:< a href =https://github.com/vuejs/vue =noreferrer> https://github.com/vuejs/vue
Bonus: I will appreciate I link to the relevant function in the VueJS code: https://github.com/vuejs/vue
推荐答案
这是Vue.js的反应系统,而不是缓存系统。
It's the reactivity system of Vue.js, not a caching system.
组件中的数据将转换为getter和setter。当您通过getter访问值时,getter会将其添加到依赖项中,当您通过setter修改该值时,setter将通知每个依赖于该值的人。
The data in a component will be convert to getters and setters. When you access a value via a getter, the getter will add it to the dependencies, and when you modify the value via a setter, the setter will notify everyone who depends on the value.
这是源代码,这个函数发生了所有的魔术: https://github.com/vuejs/vue/blob/dev/src/core/observer/index.js#L131
Here is the source code, all the magic happens in this function: https://github.com/vuejs/vue/blob/dev/src/core/observer/index.js#L131
这篇关于vuejs如何知道缓存的计算属性的依赖性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!