Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Vue Computed Properties and Watchers with Practical Examples

Tech 1

When working with Vue.js, you'll often need to respond to changes in your data. Two fundamental tools for this are computed properties and watchers. While they might seem similar at first glance, they serve different purposes and excel in different scenarios.

Computed Properties

Computed properties allow you to derive values from existing reactive data. They are particularly useful when you need to perform calculations or transformations that appear multiple times in your template.

Consider this example where you need to display a formatted username:

<template>
  <div>
    <p>{{ displayName }}</p>
  </div>
</template>

<script>
export default {
  name: 'UserProfile',
  data() {
    return {
      firstName: 'john',
      lastName: 'doe',
      userLevel: 3
    }
  },
  computed: {
    displayName() {
      const formattedFirst = this.firstName.charAt(0).toUpperCase() + this.firstName.slice(1)
      const formattedLast = this.lastName.charAt(0).toUpperCase() + this.lastName.slice(1)
      return `${formattedFirst} ${formattedLast}`
    }
  }
}
</script>

The key feature of computed properties is caching. Vue caches computed values and only recalculates them when their dependencies change. In the example above, displayName depends on firstName and lastName. If thece values don't change, accessing displayName returns the cached result immediately without re-running the computation.

Watchers

Watchers allow you to execute arbitrary code whenever a specific reactive property changes. They are ideal for handling side effects, asynchronous operations, or when you need more control than computed properties provide.

Here's a practical example of using a watcher for data synchronization:

<template>
  <div>
    <input v-model="searchQuery" placeholder="Search..." />
    <p>Results: {{ resultsCount }}</p>
  </div>
</template>

<script>
export default {
  name: 'SearchComponent',
  data() {
    return {
      searchQuery: '',
      resultsCount: 0,
      allItems: [
        { id: 1, name: 'Apple' },
        { id: 2, name: 'Banana' },
        { id: 3, name: 'Orange' },
        { id: 4, name: 'Mango' }
      ]
    }
  },
  watch: {
    searchQuery(newValue, oldValue) {
      this.filterResults()
    }
  },
  methods: {
    filterResults() {
      if (!this.searchQuery) {
        this.resultsCount = 0
        return
      }
      
      const filtered = this.allItems.filter(item =>
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
      this.resultsCount = filtered.length
    }
  }
}
</script>

Watchers also support the immediate option to trigger on initial render, and deep option for watching nested object changes.

When to Use Each

Use computed properties when:

  • You need to derive data from other reactive properties
  • The calculation is relatively simple and synchronous
  • You want automatic caching of the result

Use watchers when:

  • You need to perform operations in response to data changes
  • You're handling asynchronous operations or API calls
  • You need to update multiple data properties based on a single change
  • You need more complex logic that goes beyond simple derivation

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.