d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

How To Use Watchers in Vue

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.

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“:

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:

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.

<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.

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.

<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:

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.

<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:

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.

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this