Vue JS call a function on load example

In this post i will explain with you vue js call a function on load then in this example i will show you how to trigger vue js call a function on page load.

We mostly require to call method on page load in our application when you can do it using created option in Vue js. So i will give you full example so you can check it out.

Example:

The created method in Vue.js is executed before the component is mounted but after its data has been initialized. Let’see below example.

In Vue js 2, you would use the new Vue method.

<div id="app">
    {{ myInfo }}
    
</div>

<script type="text/javascript">
    var app = new Vue ({
       el: '#app',
       data: {
           myInfo: 'Hello!'
       },
       methods: {
           loadFunction: function () {
               console.log('Call on load...');
           }
       },
       created: function () {
           this.loadFunction();
       }
    });
</script>

in Vue js 3, you would use the createApp method:

<div id="app">
  {{ myInfo }}
  
</div>
const app = Vue.createApp({
    data() {
        return {
            myInfo: 'Hello!'
        };
    },
    methods: {
        loadFunction() {
            console.log('Call on load...');
        }
    },
    created() {
        this.loadFunction();
    }
});

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *