因此,在我的代码中,我有一个计算值today
,它允许我使用以下代码访问当前的日期、月份和年份:
today: function() {
var currentDate = new Date();
return {
day: currentDate.getDate(),
month: currentDate.getMonth(),
year: currentDate.getFullYear()
};
}
现在,据我的理解,计算属性和方法之间的区别在于,计算属性会被缓存,并且只有在它们的依赖项(例如,普通属性)发生变化时才会重新计算,而方法每次都会完全计算。
现在就我而言,没有依赖关系。因此,如果在初始化时,时间是 2017 年 12 月 24 日深夜,我会在几分钟后 25 日访问 today.day
- 我会得到原始值还是该值会是重新计算?
从技术上讲,没有任何属性是此计算属性的依赖项,因此没有任何变化。根据以下官方指南摘录,today.day
仍应等于 24
。
However, the difference is that computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.
最佳答案
事实上,答案甚至隐藏在官方指南的几行代码中:
This also means the following computed property will never update, because Date.now() is not a reactive dependency:
computed: {
now: function () {
return Date.now()
}
}
因此,在这种情况或类似情况下,您应该使用方法。
我希望这可以帮助那些不想每次遇到问题时都阅读整个指南,而更喜欢只使用 google/stackoverflow 的人。
关于methods - vue.js 是否更新依赖于方法的计算属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45821034/