This page looks best with JavaScript enabled

Watch a specific prop of an object

 ·   ·  ☕ 2 min read

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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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.

1
2
3
4
5
6
7
8
9
<script>
  export default {
    watch: {
        planets.earth.life: function(val) {
            if (!val) this.initiatePlanB();
        }
    }
  };
</script>
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things