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

Time:05-04

What is proper Vue 3 syntax for Watchers? It seems to be omitted from the docs. I'm very excited about the new features seen here: https://vuejs.org/guide/essentials/watchers.html#deep-watchers But what's the intended syntax?

CodePudding user response:

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