Watch a specific prop of an object

How do you watch a specific prop of an object? Is it useful at all?

Watch is invaluable. It allows us to react to changes in the state and keep it that way through the life cycle of the component.

Creating a watch is pretty simple. Consider the below example where we are monitoring the search text to respond to changes. You may observe that we simply do not respond to changes, but debounce it - i.e., wait for 1000ms and trigger off a request only if there was no user input within the 1000ms.

Anyway, I digress. Here’s the code for watching a simple variable -

<script>
  export default {
      <!-- rest of code -->
      watch: {
          search: function(val) {
              if (!this.awaitingSearchResults) {
              setTimeout(() => {
                  this.fetchContacts({
                  query: {
                      range_start: this.fromDateVal,
                      range_end: this.toDateVal
                  }
                  });

                  this.awaitingSearchResults = false;
              }, 1000);
              }
              this.awaitingSearchResults = true;
          }
          },
  }
</script>

This is all good since we are watching a specific variable - awaitingSearchResults.

What if you want to watch an object prop? It is a fairly common use case to respond to a specific prop changes with actions. We don’t want to watch the entire object in that case - it is too big and there can be too many side-effects to take care of.

Good news, and this is no surprise - we can watch object props just like any other string.

<script>
  export default {
    watch: {
        planets.earth.life: function(val) {
            if (!val) this.initiatePlanB();
        }
    }
  };
</script>
comments powered by Disqus