Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7699

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T06:15:09+00:00 2024-11-28T06:15:09+00:00

How to use Watchers in Vue πŸ‘€

  • 60k

In any web application, it's normal to have input data which 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 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);         }     } } 
Enter fullscreen mode Exit fullscreen mode

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);         }     } } 
Enter fullscreen mode Exit fullscreen mode

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 in 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);         }     } } 
Enter fullscreen mode Exit fullscreen mode

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> 
Enter fullscreen mode Exit fullscreen mode

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)             }         }     } } 
Enter fullscreen mode Exit fullscreen mode

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> 
Enter fullscreen mode Exit fullscreen mode

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 }); 
Enter fullscreen mode Exit fullscreen mode

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> 
Enter fullscreen mode Exit fullscreen mode

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); 
Enter fullscreen mode Exit fullscreen mode

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 value, we can use watchers to animate changes in our application. Conclusion

Watchers are a significant part of developing 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. You can find more of our Vue content here.

javascripttutorialvuewebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.