Vue.js Computed Properties and Watchers

Computed properties and watchers are powerful Vue.js features. Understanding when to use each is key to writing clean Vue code.

Computed Properties

Computed properties are cached and only update when dependencies change:

computed: {
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  activeUsers() {
    return this.users.filter(u => u.isActive);
  },
  total() {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }
}

Watchers

Watchers react to changes – good for side effects:

watch: {
  searchQuery(newVal, oldVal) {
    // Debounced API call
    this.debouncedSearch(newVal);
  },
  '$route'(to, from) {
    // React to route changes
    this.fetchData();
  }
}

When to Use Which

  • Computed: Deriving values, templates, getters
  • Watch: Side effects, async operations, complex reactions

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

WordPress database error: [User 'dataadl336' has exceeded the 'max_questions' resource (current value: 40000)]
SELECT p.ID FROM cmxg4_posts AS p WHERE (p.post_date < '2019-06-27 10:00:00' OR (p.post_date = '2019-06-27 10:00:00' AND p.ID < 15386)) AND p.post_type = 'post' AND p.post_status = 'publish' ORDER BY p.post_date DESC, p.ID DESC LIMIT 1

WordPress database error: [User 'dataadl336' has exceeded the 'max_questions' resource (current value: 40000)]
SELECT p.ID FROM cmxg4_posts AS p WHERE (p.post_date > '2019-06-27 10:00:00' OR (p.post_date = '2019-06-27 10:00:00' AND p.ID > 15386)) AND p.post_type = 'post' AND p.post_status = 'publish' ORDER BY p.post_date ASC, p.ID ASC LIMIT 1

WordPress database error: [User 'dataadl336' has exceeded the 'max_questions' resource (current value: 40000)]
SELECT SQL_CALC_FOUND_ROWS cmxg4_comments.comment_ID FROM cmxg4_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 15386 AND comment_type NOT IN ('note') ORDER BY cmxg4_comments.comment_date_gmt ASC, cmxg4_comments.comment_ID ASC

Leave a comment

Your email address will not be published. Required fields are marked *

WordPress database error: [User 'dataadl336' has exceeded the 'max_questions' resource (current value: 40000)]
SELECT option_value FROM cmxg4_options WHERE option_name = 'akismet_comment_nonce' LIMIT 1

This site uses Akismet to reduce spam. Learn how your comment data is processed.

WordPress database error: [User 'dataadl336' has exceeded the 'max_questions' resource (current value: 40000)]
SELECT option_value FROM cmxg4_options WHERE option_name = 'cookie_consent_template' LIMIT 1

WordPress database error: [User 'dataadl336' has exceeded the 'max_questions' resource (current value: 40000)]
SELECT option_value FROM cmxg4_options WHERE option_name = 'jpsq_sync_checkout'

WordPress database error: [User 'dataadl336' has exceeded the 'max_questions' resource (current value: 40000)]
SELECT COUNT(*) FROM cmxg4_jetpack_sync_queue WHERE queue_id = 'sync'