Vue 3 provides an interesting feature known as watchers. There are cases when we need to perform some side effects in reaction to some state changes. Vue 3 Watchers with Composition API helps us handle such scenarios.

The state changes can be triggered by any events such as mutating the DOM or changing a piece of state based on the results of an async operation.

Note that watchers are different from VueJS Computed Properties using which we can declaratively calculate derived values.

1 – Basic Vue 3 Watchers Example

VueJS provides us an in-built watch() function to create a watcher. We can use this function to trigger a callback whenever a piece of reactive state changes.

See below example:

<script setup>
import { ref, watch } from 'vue'

const something = ref('')
const greeting = ref('')
const language = ref('')

watch(something, async (newSomething) => {
  if (newSomething.length > 1) {
    greeting.value = 'Preparing to greeting...'
    try {
      const res = await fetch('https://www.greetingsapi.com/random')
      const response = await res.json()
      greeting.value = response.greeting
      language.value = response.language
    } catch (error) {
      answer.value = 'Error while calling the API. ' + error
    }
  }
})
</script>

<template>
  <p>
    Say something:
    <input v-model="something" />
  </p>
  <p>{{ greeting }}</p>
  <p>{{language}}</p>
</template>

Let us walkthrough the example code.

  • First, we have the import statement where we import the watch function from vue itself.
  • Next, we declare a few state variables using ref(). If interested, you can read more about VueJS Reactivity.
  • Then, we call the watch() function where we pass something. Basically, something is the variable we are watching using the VueJS watcher.
  • In the associated callback function, we simply check whether the something variable contains some character. If it does, we make a call to a greeting generator API.
  • Based on the response from the random greeting API, we update the greeting and language variables.

2 – Vue 3 Watchers Source Type

We can also have different source types for the Vue 3 watch() function.

In the previous example, we used a ref variable something.

watch(something, async (newSomething) => {
  if (newSomething.length > 1) {
    greeting.value = 'Preparing to greeting...'
    try {
      const res = await fetch('https://www.greetingsapi.com/random')
      const response = await res.json()
      greeting.value = response.greeting
      language.value = response.language
    } catch (error) {
      answer.value = 'Error while calling the API. ' + error
    }
  }
})

Also, we can have a getter function as the source of a watch() function. Check the below example:

watch(
  () => x.value + y.value,
  (sum) => {
    console.log(`sum of x + y is: ${sum}`)
  }
)

In this example, we are basically watching the sum of two variables x and y.

Lastly, we can also have an array of multiple sources as the input to the watch() function.

watch([x, () => y.value], ([newX, newY]) => {
  console.log(`x is ${newX} and y is ${newY}`)
})

In the above example, one input is x while the second input is a getter function.

Depending on our requirement, we can use the appropriate source type for the Vue 3 Watcher.

3 – Vue 3 Watch Reactive Object

When dealing with reactive objects, we can’t directly watch a property of the reactive object.

See below example:

const counter = reactive({ count: 0 })

watch(counter.count, (count) => {
  console.log(`count is: ${count}`)
})

Ultimately, the above indicates that we are trying to watch a number. This won’t work as expected.

In case we want to watch the count property of the counter object, we need to use the getter approach.

Check the below snippet.

const counter = reactive({ count: 0 })

watch(
  () => counter.count,
  (count) => {
    console.log(`count is: ${count}`)
  }
)

Conclusion

As you can see, Vue 3 watchers are an extremely useful tool. Vue 3 Watchers with Composition API are quite easy to implement with different source types. We can choose the source type based on our requirement.

The watch() function is lazy in nature. However, in case you are looking for eager execution of callback, check out how to use Vue 3 WatchEffect.

Want to learn more Vue 3 use-cases? Check out this post on how to create a Vue 3 carousel.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: VueJS

0 Comments

Leave a Reply

Avatar placeholder

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