Sobes.tech
Middle

What are computed and watchers in Vue?

sobes.tech AI

Answer from AI

In Vue.js, computed properties and watchers are used for reactive data tracking but serve different purposes:

  • Computed are properties that are calculated based on reactive data and are automatically cached. They are recalculated only when their dependent data changes. They are used for deriving values that depend on other data.

    Example:

    computed: {
      fullName() {
        return this.firstName + ' ' + this.lastName;
      }
    }
    

    Here, fullName will automatically update when firstName or lastName changes.

  • Watchers are functions that observe changes to specific data and allow executing side effects (such as asynchronous operations, API calls) when these data change.

    Example:

    watch: {
      searchQuery(newVal, oldVal) {
        this.fetchResults(newVal);
      }
    }
    

    Here, when searchQuery changes, the method fetchResults is called.

Summary:

  • Use computed for deriving values based on reactive data.
  • Use watchers for performing actions when data changes, especially if side effects are needed.
What are computed and watchers in Vue? — Frontend - sobes.tech