How to use mounted Hook In Vue
In this approach, are using the mounted lifecycle hook. We have defined a function as loadFn which is automatically called using a mounted hook. This hook is executed when the Vue instance is mounted to the DOM.
Syntax:
mounted() {
// logic to call function
}
Example: Below is the implementation of the above-discussed approach.
HTML
<!DOCTYPE html> < html > < head > < title >Example 1</ title > < script src = "https://cdn.jsdelivr.net/npm/vue@2" > </ script > < style > body { font-family: 'Arial', sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; } </ style > </ head > < body > < div id = "app" > < h1 style = "color: green;" > {{ message }} </ h1 > < h3 > Approach 1: Using mounted Hook </ h3 > </ div > < script > new Vue({ el: '#app', data: { message: 'w3wiki', }, mounted() { this.loadFn(); }, methods: { loadFn() { alert ('Page Load. Function Executed'); }, }, }); </ script > </ body > </ html > |
Output:
How to Call a Vue.js Function on Page Load ?
In this article, we will learn how to call a vue.js function on page load in VueJS. We will explore two different approaches with practical implementation in terms of examples and outputs.
Table of Content
- Using mounted Hook
- Using created Hook