Vue.js Watchers

A Vue watcher allows you to listen to the component data and run whenever a particular property changes

⭐️ 👀 2023 WEB DEVELOPMENT BOOTCAMP starting in days! Join the waiting list to reserve your spot in my 10-weeks cohort course and learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much much more! 👀 ⭐️

A watcher is a special Vue.js feature that allows you to spy on one property of the component state, and run a function when that property value changes.

Here’s an example. We have a component that shows a name, and allows you to change it by clicking a button:

<template>
  <p>My name is {{name}}</p>
  <button @click="changeName()">Change my name!</button>
</template>

<script>
export default {
  data() {
    return {
      name: 'Flavio'
    }
  },
  methods: {
    changeName: function() {
      this.name = 'Flavius'
    }
  }
}
</script>

When the name changes we want to do something, like printing a console log.

We can do so by adding to the watch object a property named as the data property we want to watch over:

<script>
export default {
  data() {
    return {
      name: 'Flavio'
    }
  },
  methods: {
    changeName: function() {
      this.name = 'Flavius'
    }
  },
  watch: {
    name: function() {
      console.log(this.name)
    }
  }
}
</script>

The function assigned to watch.name can optionally accept 2 parameters. The first is the new property value. The second is the old property value:

<script>
export default {
  /* ... */
  watch: {
    name: function(newValue, oldValue) {
      console.log(newValue, oldValue)
    }
  }
}
</script>

Watchers cannot be looked up from a template as you can with computed properties.

One more thing! ⚠️ ✋

At the end of January I will organize the Web Development Bootcamp.

It's a 10-weeks long cohort online course where I will guide you to becoming a Web Developer.

It's not "just a course". It's a big event I organize once a year.

We'll start from zero, learn the fundamentals of Web Development, HTML CSS, JavaScript, Tailwind, Git, using the command line, VS Code, GitHub, Node.js, we'll then learn React, JSX, how to use PostgreSQL, Astro, Next.js, Prisma, deploying on Netlify/DigitalOcean/Fly/Vercel and much more! 

At the end of the first 10 weeks you'll know how to create web sites and web applications and I'll unlock you the 2nd phase of the Bootcamp: you will get access to a large number of projects exclusive to the Bootcamp graduates, so you can follow my instructions to build things like private areas with authentication, clones of popular sites like Twitter YouTube Reddit, create e-commerce sites, and much much more.

Because once you got the fundamentals, you only learn by working on real, exciting projects.

To find out more, visit bootcamp.dev