Vue中的方法与计算

Vue.js中的方法和计算值之间的主要区别是什么?

它们看起来相同且可互换。

小宇宙飞云2020/03/09 22:55:11

来自 docs

..computed属性根据其依赖关系进行缓存。仅当某些依赖项已更改时,计算属性才会重新评估。

另一方面,如果您想缓存数据,则使用Computed属性,如果您不希望缓存数据,请使用简单的Method属性。

ASamJim2020/03/09 22:55:11

Here’s a breakdown of this question.

When to use methods

  • To react to some event happening in the DOM
  • To call a function when something happens in your component.
  • You can call a method from computed properties or watchers.

When to use computed properties

  • You need to compose new data from existing data sources
  • You have a variable you use in your template that’s built from one or more data properties
  • You want to reduce a complicated, nested property name to a more readable and easy to use one (but update it when the original property changes)
  • You need to reference a value from the template. In this case, creating a computed property is the best thing, because it’s cached.
  • You need to listen to changes of more than one data property