Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Mastering Vue 3 Watch: Reactive Data Monitoring Essentials

Tech May 9 3

Vue 3's watch utility serves as a fundamental mechanism for tracking changes in reactive state and executing specific logic upon modification. Unlike previous versions, it offers granular control within the Composition API.

Supported Reactive Sources

The watch function can observe four primary types of sources:

  1. Variables defined with ref.
  2. Objects defined with reactive.
  3. Functions returning a value (getter functions).
  4. Arrays containing any of the above sources.

Basic Traccking with Ref Variables

Consider a scenario where a simple numeric counter is managed using ref. To monitor updates to this primitive type, you pass the variable directly into the watch function.

<template>
  <div class="tracker">
    <h2>Total Count: {{ stepCount }}</h2>
    <button @click="increaseStep">Add Step</button>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue'

  let stepCount = ref(0)

  function increaseStep() {
    stepCount.value++
  }

  // Observe changes to stepCount
  watch(stepCount, (newVal, oldVal) => {
    console.log('Change detected:', newVal, oldVal)
  })
</script>

<style scoped>
  .tracker {
    padding: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
  }
</style>

To limit the lifespan of the watcher, you can capture the stopper function returned by watch:

const stopTracking = watch(stepCount, (newVal, oldVal) => {
  console.log(newVal, oldVal)
  if (newVal >= 5) {
    stopTracking()
  }
})

This approach ensures the callback ceases execution once the condition is met, optimizing resource usage.


Tracking Objects Defined by Ref

When monitoring an object wrapped in ref, the behavior differs from primitive types. The default watch tracks the reference address. Modifying internal properties does not trigger a re-run unless deep observation is enabled.

Consider the following configuration object:

<template>
  <div class="config-panel">
    <p>App Name: {{ appSettings.name }}</p>
    <p>Version: {{ appSettings.version }}</p>
    <button @click="modifyName">Update Name</button>
    <button @click="replaceSettings">Replace Object</button>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue'

  let appSettings = ref({
    name: 'MyApplication',
    version: '1.0.0'
  })

  function modifyName() {
    appSettings.value.name += '_v2'
  }

  function replaceSettings() {
    appSettings.value = { name: 'NewApp', version: '2.0.0' }
  }

  // Standard Watch - Tracks Address Reference
  watch(appSettings, (newVal, oldVal) => {
    console.log('Object Watch Triggered')
  })
</script>

Behavior Analysis:

  • Internal Updates: Clicking "Update Name" modifies appSettings.value.name. Since the object reference remains the same, the watcher does not fire automatically without additional options.
  • Replacement: Clicking "Replace Object" assigns a new object. This changes the address reference, triggering the callback immediately.

Deep Observation To detect property mutations within the object, enable deep mode or use the deep option:

watch(appSettings, (newVal, oldVal) => {
  console.log('Deep watch:', newVal, oldVal)
}, {
  deep: true
})

Additionally, setting immediate: true forces the callback to execute once right after the watcher initializes, capturing the current state before any changes occur.


Comparison with Vue 2

In Vue 2, watch functionality was primarily defined within the component's watch options object, binding specific paths to handlers statically. In contrast, Vue 3 utilizes a functional appproach, allowing dynamic watcher creation anywhere in the script setup. This shift provides superior flexibility, enabling multi-source watching and deeper integration with reactive primitives like refs and getters compared to the rigid Options API pattern.

Tags: Vue3

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.