DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • 5 Steps to Strengthen API Security

Trending

  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Contextual AI Integration for Agile Product Teams
  • Navigating the LLM Landscape: A Comparative Analysis of Leading Large Language Models
  • Role of Cloud Architecture in Conversational AI

How To Use Watchers in Vue

Let's Learn about how watchers work in Vue.

By 
Johnny Simpson user avatar
Johnny Simpson
DZone Core CORE ·
Feb. 26, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
8.0K Views

Join the DZone community and get the full member experience.

Join For Free

In any web application, it's normal to have input data that alters a page. For example, a user may update their username, or submit a post. In vue, we can watch for these changes using watchers. Watchers allow us to check on a specific data element or prop and see if it's been altered in any way.

If you are brand new to Vue, get started with our guide on making your first Vue app here, before diving into watchers.

Using Watchers in Vue

When we make new components in Vue, that is, a .vue file we can watch for changes in data or props by using the watch. For example, the below code will watch for a change in the data element pageData, and run a function according to the value it is changed to.

JavaScript
 
export default {
    name: "MyComponent",
    data() {
        return {
            pageData: [{
                name : "Some Page",
                page : "/article/some-page"
            }]
        }
    },
    watch: {
        pageData: function(value) {
            // If "pageData" ever changes, then we will console log its new value.
            console.log(value);
        }
    }
}

Watching for Prop Changes in Vue

Similarly, we can watch for prop changes using the same methodology. The below example watches for a change in a prop called "name":

JavaScript
 
export default {
    name: "MyComponent",
    props: {
        name: String
    },
    watch: {
        name: function(value) {
            // Whenever the prop "name" changes, then we will console log its value.
            console.log(value);
        }
    }

Getting the Old Value With Vue Watch

If we want to retrieve the old value, i.e. the value that the data or prop was before the change, we can retrieve that using the second argument within a watch function. For example, the below code will now console log both the new value of pageData, and the old value:

JavaScript
 
export default {
    name: "MyComponent",
    data() {
        return {
            pageData: [{
                name : "Some Page",
                page : "/article/some-page"
            }]
        }
    },
    watch: {
        pageData: function(newValue, oldValue) {
            // If "pageData" ever changes, then we will console log its new value.
            console.log(newValue, oldValue);
        }
    }
}

Watchers in Components

Now that we have an idea of how watchers work - Let's look at a real-life example. The below component has a counter, which when clicked, increases the value of a data value called totalCount. We watch for changes in totalCount and given its value, we will display that on the page.

Vue.js Component
 
<template>
    <button @click="totalCount = totalCount + 1">Click me</button>
    <p>{{ message }}</p>
</template>

<script>
export default { 
    name: "Counter",
    data() {
        return {
            // "message" will show up in the template above in {{ message  }}
            message: "You haven't clicked yet!",
            // This is the total number of times the button has been clicked
            totalCount: 0
        }
    },
    watch: {
        // Watch totalCount for any changes
        totalCount: function(newValue) {
            // Depending on the value of totalCount, we will display custom messages to the user
            if(newValue <= 10) {
                this.message = `You have only clicked ${newValue} times.`;
            }
            else if(newValue <= 20) {
                this.message = `Wow, you've clicked ${newValue} times!`;
            }
            else {
                this.message = `Stop clicking, you've already clicked ${newValue} times!`;
            }
        }
    }
}
</script>

Watching for Deep or Nested Data Changes in Vue

Vue only watches data changes in objects or arrays at its first level. So if you expect changes at a lower level, let's say pageData[0].name, we need to do things slightly differently. This is called deep watching, since we are watching nested or deep data structures, rather than just shallow changes.

So deep watchers are a way to check for data changes within our object itself. They follow the same structure, except we add deep: true to our watcher. For example, the below code will note changes in the name and URL attributes of the pageData object.

JavaScript
 
export default {
    name: "MyComponent",
    data: {
        return {
            pageData: [{
                name: "My Page",
                url: "/articles/my-page"
            }]
        }
    },
    watch: {
        pageData: {
            deep: true,
            handler: function(newValue, oldValue) {
                // If name or page updates, then we will be able to see it in our
                // newValue variable
                console.log(newValue, oldValue)
            }
        }
    }
}

Watchers Outside of Components

If you want to use a watcher outside of a component, you can still do that using the watcher() function. An example is shown below where we watch for the change in a variable called totalCount, outside of the watch: {} object.

Deep Watchers

Note: deep watchers are great, but they can be expensive with very large objects. If you are watching for mutations in a very big object, it may lead to some performance problems.

Since we wrap the value of totalCount in ref() Vue notes it as reactive. That means we can use it with our watcher.

JavaScript
 
<script setup>
import { ref, watch } from 'vue'

let totalCount = ref(0)

watch(totalCount, function(newValue, oldValue) {
    console.log(newValue, oldValue);
})
</script>

You can easily turn these into deep watchers, too, by adding the deep: true option to the end:

JavaScript
 
watch(totalCount, function(newValue, oldValue) {
    // Similar to before, only it will watch the changes at a deeper level
    console.log(newValue, oldValue);
}, { deep: true });

That means you can still leverage the value of watchers, without having them contained within export default.

Vue Watch Getter Function

Using this format, we can set the first argument in watch to a function, and use it to calculate something. After that, the calculated value then becomes watched. For example, the below code will add both x and y together, and watch for its change.

JavaScript
 
<script setup>
import { ref, watch } from 'vue'

let x = ref(0);
let y = ref(0);
watch(() => x + y, function(newValue, oldValue) {
    console.log(newValue, oldValue);
})
</script>

watchEffect

watchEffect is a brand new addition to Vue 3, which watches for changes of any reactive reference within it. As mentioned before, we can tag a variable as reactive using the ref() function. When we use watchEffect, then, we don't explicitly reference a particular value or variable to watch - it simply watches any reactive variable mentioned inside it. Here is an example:

JavaScript
 
import { ref, watch } from 'vue'

let x = ref(0);
let y = ref(0);

watchEffect(() => {
    console.log(x.value, y.value);
});

++x.value; 
++y.value; // Logs (x, y);

Things To Note About watchEffect

  • It will run once at the start - without any changes to your reactive data. That means the above example will console log 0, 0 when you open the page.
  • For deep reference changes, use watch - watchEffect would be very inefficient if it did a deep check since it would have to iterate over many different variables many times.

When To Use Watchers

Watchers have many applications, but the key ones are:

  • API requests - requesting data from a server and then watching for the response via a watcher. Websocket requests - watching for changes in data structures gathered from websockets.
  • Data changes requiring logic - waiting for a change in data, and then using that value to change the application based on logic within the watcher function.
  • When moving between different pieces of data - since we have both the new and old values, we can use watchers to animate changes in our application. Conclusion

Watchers are a significant part of development in Vue 3. With watchers, we can achieve reactivity for data with minimal code. As such, figuring out when and why to use them is an important part of developing any Vue application.

Data element

Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • 5 Steps to Strengthen API Security

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!