Skip to content

How to Properly Watch for Nested Data in Vue.js

Let’s discuss how to properly watch for prop variation and see what method is right for your case.

You can use a deep watcher, however, it will detect any changes to the objects in the item array and additions to the array:


javascript
watch: {
  item: {
     handler(val){
       // do stuff
     },
     deep: true
  }
}

Here, you should set deep to true when watching an array or an object to tell Vue that it should watch the nested data for changes.

To not watch for every change on the top level object, simply watch a computed property instead:


javascript
// Vue 2 Options API
const app = new Vue({
  el: '#app',
  computed: {
    foo() {
      return this.item.foo;
    }
  },
  watch: {
    foo() {
      console.log('Foo Changed!');
    }
  },
  data: {
    item: {
      foo: 'foo'
    }
  }
})
javascript
// Vue 3 Composition API
import { ref, computed, watch } from 'vue'

const item = ref({ foo: 'foo' })
const foo = computed(() => item.value.foo)

watch(foo, (newVal) => {
  console.log('Foo Changed!')
})

Watched props are sometimes confused with computed properties, but they serve different purposes. Computed properties are read-only and should be used for deriving values based on reactive data. If you need to perform side effects or update state in response to changes, use a watcher instead. Mutating props directly in a watcher can cause issues, as both the parent and child components would be updating the same state.

Dual-run preview — compare with live Symfony routes.