In Vue.js, if you want to call a function during page load, you typically place the function within the lifecycle hooks of the Vue instance, such as created or mounted. These hooks are the most commonly used for executing code after the instance is created.
Using created Hook
The created hook is called immediately after the instance is created, at which point the component's data has been initialized but the DOM has not yet been rendered. This is ideal for data initialization.
Example:
javascriptnew Vue({ el: '#app', data() { return { message: 'Hello Vue!' } }, created() { this.sayHello(); }, methods: { sayHello() { console.log('Hello from Vue!'); } } });
In this example, the sayHello function is called immediately after the Vue instance is created, i.e., during page load.
Using mounted Hook
The mounted hook is called after the instance is mounted, at which point all DOM structures have been fully rendered and are ready for manipulation. This is the appropriate time for DOM operations or initializing libraries that depend on the DOM.
Example:
javascriptnew Vue({ el: '#app', data() { return { message: 'Hello Vue!' } }, mounted() { this.sayHello(); }, methods: { sayHello() { console.log('Hello from the mounted DOM!'); } } });
In this example, the sayHello function is called after the DOM is fully rendered and mounted to the page, which is suitable for DOM operations.
Summary
Choosing between created and mounted hooks depends on your needs:
- Use
createdif you need to perform data operations before the DOM is rendered. - Use
mountedif you need to perform operations after the DOM is rendered (e.g., directly manipulating the DOM or initializing external libraries that depend on the DOM).
This approach ensures your code remains logically clear and efficient.