·
0 min read
Vue Tip: Trigger Watcher Immediately
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:
Vue Tip: Use Multiple v-model Bindings
Sometimes Vue.js components need to have multiple v-model bindings.
Vue Tip: Simple Expressions in Templates
Vue component templates should only include simple expressions, with more complex expressions refactored into computed properties or methods.