What is proper Vue 3 <Setup Script/> syntax for Watchers?

Viewed 1270
1 Answers

This is a basic example of a watch inside the script setup syntax:

<template>
  <div>
    <input type="text" v-model="user.name" placeholder="Name" />
    <input type="text" v-model="user.lastname" placeholder="Lastname" />
    {{ nameUpdatesCount }}
  </div>
</template>
<script setup>
import { reactive, ref, watch } from "vue";

const user = reactive({ name: "", lastname: "" });
const nameUpdatesCount = ref(0);

const increaseNameUpdatesCount = () => {
  nameUpdatesCount.value++;
};

watch(user, (newValue, oldValue) => {
  console.log(newValue, oldValue);
  increaseNameUpdatesCount();
});
</script>

In the example above, the watcher will be triggered every time that you write or delete something in the inputs. This happens because the name property changes its value. After that, the increaseNameUpdatesCount method is called, and you will see the nameUpdatesCount be incremented by one.

Related