Categories
JavaScript Vue

How to Deep Watch Data in a Vue App

Spread the love

There are a few ways to deep watch data in a Vue app.

We can add a deep watcher by writing:

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

The most import part is the deep property. We must set it to true to enable deep watch on an object property.

We can create a computed property to return a value based on one or more values.

For example, we can write:

new Vue({
  el: '#app',
  computed: {
    foo() {
      return this.item.foo;
    }
  },
  data: {
    item: {
      foo: 'foo'
    }
  }
})

The foo computed property is computed by using the value of this.item.foo.

We can reference the value as this.foo in our component code and write:

{{ foo }}

to reference it in the template.

We can also write:

watch:{
   'item.foo': function (newVal, oldVal){
       // ...
   },
   'item.bar': function(newVal, oldVal){
       // ...
   }
}

Then we watch the value of item.foo and item.bar in our code.

newVal has the new value and oldVal has the old value of each property.

We can watch data in a few ways with Vue apps.

If we just need a value that’s derived from one or more other values, then we use computed properties.

Otherwise, we can use deep watchers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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