Sobes.tech
Middle

What are 'watch' and 'computed' in Vue.js, and how do they work?

sobes.tech AI

Answer from AI

watch (observers)

  • Used for reacting to changes in a specific reactive property.
  • Allows performing asynchronous operations, delaying execution, or performing complex calculations when the property value changes.
  • Configured with the watch option inside a component.
  • Can have parameters like handler (handler function), deep (deep observation of nested objects/arrays), and immediate (execute handler upon component creation).

Example:

watch: {
  // Watches for changes in the `firstName` property
  firstName(newValue, oldValue) {
    console.log(`Name changed from ${oldValue} to ${newValue}`);
  },
  // Deeply observes the `userInfo` object
  userInfo: {
    handler(newValue, oldValue) {
      console.log('User information has been changed.');
    },
    deep: true
  }
}

computed (computed properties)

  • Used for declarative creation of dependent reactive data.
  • The result is cached until its reactive dependencies change.
  • Computed lazily, only when accessed.
  • Configured with the computed option inside a component.
  • Must return a value.

Example:

computed: {
  // Computes full name based on firstName and lastName
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  // Filters the list of users
  filteredUsers() {
    return this.users.filter(user => user.isActive);
  }
}

Main differences

Attribute watch computed
Purpose React to property changes Calculate dependent data
Caching No Yes (based on dependencies)
Laziness No Yes
Return value No (performs side effects) Yes (returns computed value)
Asynchronous Yes No
Syntax Object with handler functions Object with functions returning values

Use computed to obtain reactive data derived from other data. Use watch to perform side effects (e.g., API calls, DOM modifications) when a reactive property changes, or to execute more complex logical reactions.