Javascript is required
ยท
0 min read

Vue Tip: Trigger Watcher Immediately

Vue Tip: Trigger Watcher Immediately Image

The watch hook provides an option that its callback function is called immediately:

1<template>
2  <input v-model="counter" />
3</template>
4
5<script setup>
6import { ref, watch } from 'vue'
7
8const counter = ref(0)
9
10watch(
11  counter,
12  (newValue, oldValue) => {
13    console.log('The new counter value is: ' + counter.value)
14  },
15  { immediate: true }
16)
17</script>

This code will generate the output New counter value is: 0 after the setup method is executed initially. It will also create a log message for all subsequent counter-value changes.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.