Vue Tip: Trigger Watcher Immediately

Michael Hoffmann
Dec 2, 2021
| 1 min read
| 117 views
Michael Hoffmann
Dec 2, 2021
1 min read
| 117 views
Script

The watch hook provides an option that its callback function is called immediately:
<template> <input v-model="counter" /></template><script setup>import { ref, watch } from 'vue'const counter = ref(0)watch( counter, (newValue, oldValue) => { console.log('The new counter value is: ' + counter.value) }, { immediate: true })</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 Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.
Vue Tip: Use Multiple v-model BindingsNov 25, 2021
Vue Tip: Simple Expressions in TemplatesDec 10, 2021
Show comments