Mokkapps Logo

Vue Tip: Trigger Watcher Immediately

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
December 02, 2021
1 Minuten Lesezeit
|
- Ansichten

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 tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github