Open In App

How to Trigger Watchers on Initialization in Vue.js ?

Last Updated : 07 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Vue.js is a popular JavaScript framework used for building user interfaces. One of the main features of vue.js is the reactivity system it helps us in developing data-driven applications i.e. if data changes then the change is reflected on the user interface. In this article, we will see how we can trigger watchers on initialization in Vue.js.

One of the ways to use this reactivity system in Vue.js is to use watchers, watchers are functions that are triggered whenever there is a change in data. However, we might want the function to be triggered on the application’s initialization rather than waiting for a change in data. This is what we will learn in this article how we can create a watcher that is triggered on initialization of your application.

Watchers in Vue.js are the functions that are used to watch changes in data property in vue.js whenever data is changed watcher is triggered and it calls the function with the old value and the new value of the data property. This helps us in choosing the right action that needs to perform on changes in data property such as updating the user interface or make an API call.

Triggering watcher on Initialization: By default, the watcher is triggered only when the data property changes but if we want to trigger it on initialization then we use the ‘immediate’ option when defining the watcher. The immediate option tells vue.js to trigger the function as soon as the component is created instead of waiting for changes to occur.

Syntax:

new Vue({
    data: {
        message: 'Hello, World!'
    },
    watch: {
        message: {
            immediate: true,
            handler: function(newVal, oldVal) {
                console.log('Message changed from', 
                            oldVal, 'to', newVal)
            }
        }
    }
})

As you can see (in the above syntax) the watcher is defined with an immediate property set as true, which triggers the watcher as soon as the component is created.

Note: If we use the immediate option, then the watcher function will be called twice once when the component is created and the other when the data property changes, if you want it to run only once then you can add a check to see if the value is changed or not if it is changed then we don’t run the function.

Syntax:

new Vue({
    data: {
        message: 'Hello, World!'
    },
    watch: {
        message: {
            immediate: true,
            handler: function(newVal, oldVal) {
                if (newVal !== oldVal) {
                    console.log('Message changed from', 
                                oldVal, 'to', newVal)
                }
            }
        }
    }
})

In the above example, we have added a check to see if the data property is changed before sending the message to the console.

Approach 1: Using a computed property

In this approach, we use a computed property that returns the initial value of the data property that we want to watch and then we watch the computed property for changes in the data property. This way the watcher will be triggered on initialization because the computed property depends on the data property.

Example: This is basic example that illustrates triggering the watchers on initialization by implementing the computed property in Vue.js

HTML




<template>
    <div>
        <h1>GeeksforGeeks</h1>
        <h3>
              This is article on how to trigger 
            watchers on initialization
          </h3>
        <p>{{ message }}</p>
    </div>
</template>
  
<script>
    export default {
        data() {
            return {
                message: "Hello, World! Using computed property",
            };
        },
        computed: {
            messageComputed: {
                get() {
                    return this.message;
                },
                set(value) {
                    this.message = value;
                },
            },
        },
        watch: {
            messageComputed: {
                immediate: true,
                handler(newVal, oldVal) {
                    console.log(
                      `Message changed from ${oldVal} to ${newVal}`);
                },
            },
        },
    };
</script>


In this example, we defined a computed property called ‘messageComputed’ that returns the value of the ‘message‘ data property and then we define a watcher on the ‘messageComputed’  property which will be triggered on initialization because it depends on ‘message’ data property. the watcher function will log a message into the console with old value and new value.

Output:

 

Approach 2: Using lifecycle Hook

In this approach, we can use the Vue.js lifecycle hook to call a method that sets up a watcher on the data property that we want to watch. To do so, we can use the lifecycle hook ‘created’. Makes sure that the component is fully initialized before setting the watcher

Example: In this example, we use the ‘created’ lifecycle hook to set up a watcher on the ‘message’ data property. We also set the immediate option to true to ensure that the watcher is triggered immediately when the component is created. The watcher function will log a message to the console with the old and new values of the ‘message’ property.

HTML




<template>
    <div>
        <h1>GeeksforGeeks</h1>
        <h3>
              This is article on how to trigger 
            watchers on initialization
          </h3>
        <p>{{ message }}</p>
    </div>
</template>
  
<script>
    export default {
        data() {
            return {
                message: "Hello, World! Using lifecycle Hook",
            };
        },
        created() {
            this.$watch(
                "message",
                (newVal, oldVal) => {
                    console.log(
                      `Message changed from ${oldVal} to ${newVal}`);
                },
                {
                    immediate: true,
                }
            );
        },
    };
</script>


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads