Method vs Computed in Vue

后端 未结 7 544
说谎
说谎 2020-11-28 01:00

What is the main difference between a method and a computed value in Vue.js?

They look the same and interchangeable.

7条回答
  •  情书的邮戳
    2020-11-28 01:36

    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

提交回复
热议问题