Javascript
Difference between the created and mounted events in Vuejs
Understanding the lifecycle of a Vue.js component is crucial for building dynamic and efficient web applications. Two lifecycle hooks often cause confusion, especially for newcomers: created() and mounted(). While both play vital roles in component initialization, they differ significantly in terms of timing and access to the Document Object Model (DOM). Mastering these nuances unlocks a deeper understanding of Vue.js and allows you to leverage their respective strengths for more robust application development. This article delves into the core differences between created() and mounted(), providing clear examples and practical insights to guide your Vue.js journey.
Component Creation vs. DOM Mounting
The core distinction lies in when these hooks are triggered. created() is called after the component instance is created, but before the component’s template is rendered into the DOM. This means data properties are reactive, data fetching can begin, and events can be set up, but the DOM itself is inaccessible. mounted(), on the other hand, is called after the component’s template has been compiled and inserted into the DOM. This provides full access to the component’s template, enabling direct DOM manipulation, integration with third-party libraries, and more.
Think of it like building a house. created() is like laying the foundation and framing the walls – the essential structure is in place, but you can’t move in yet. mounted() is like finishing the interior and moving your furniture in – everything is ready for use.
When to Use created()
created() is ideal for tasks that don’t require DOM access. This includes:
- Initializing data properties from an API.
- Setting up event listeners for component communication.
- Subscribing to data stores like Vuex.
For instance, fetching data from an external API upon component creation is a common use case:
javascript created() { fetch(’/api/data’) .then(res => res.json()) .then(data => { this.items = data; }); } When to Use mounted()
mounted() is essential for tasks requiring DOM manipulation or interaction with external libraries that rely on the DOM. This includes:
- Integrating with third-party JavaScript libraries like jQuery or D3.js.
- Directly manipulating DOM elements for animations or dynamic styling.
- Accessing and modifying elements based on user interactions.
For example, integrating a charting library often requires the DOM to be ready:
javascript mounted() { const chart = new Chart(this.$refs.chartCanvas, { // Chart configuration }); } Choosing the Right Hook: A Practical Example
Imagine building a dynamic image gallery. You would use created() to fetch image data from an API. Then, in mounted(), you’d initialize a carousel library (like Owl Carousel) that requires access to the DOM elements containing the images. This ensures the carousel properly initializes after the images are rendered.
Common Pitfalls and Best Practices
A common mistake is attempting to access DOM elements within created(). This leads to errors because the DOM hasn’t been rendered yet. Ensure DOM-dependent operations reside within mounted(). Also, avoid heavy DOM manipulations inside mounted() that could impact initial render performance.
- Fetch data in
created(). - Manipulate the DOM in
mounted(). - Optimize DOM operations for performance.
These best practices improve code clarity and application efficiency. By understanding the lifecycle phases, you write more predictable and maintainable Vue.js code.
Infographic Placeholder: Visualizing the Vue.js Lifecycle
Learn more about Vue.js component lifecycle.FAQ
Q: What happens if I modify data within mounted()?
A: Modifying data within mounted() will trigger reactivity updates, but ensure DOM manipulations based on that data are handled correctly to avoid race conditions.
For further reading on Vue.js lifecycle hooks, refer to these resources:
Vue.js Lifecycle Hooks Understanding Vue.js Component Lifecycle Understanding Vue.js Component Lifecycle Hooks (CSS-Tricks)By understanding the distinction between created() and mounted(), you can write more efficient and maintainable Vue.js components. Leverage created() for pre-DOM initialization tasks and mounted() for DOM interactions. This mindful approach enhances application performance and contributes to a cleaner codebase. Explore the provided resources and examples to deepen your Vue.js expertise, and start building more robust and dynamic web applications. Consider exploring related topics like Vue.js component communication and state management with Vuex to further enhance your skills.
Question & Answer :
Vue.js documentation describes the created and mounted events as follows:
created
Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
mounted
Called after the instance has just been mounted where el is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called.
This hook is not called during server-side rendering.
I understand the theory, but I have 2 questions regarding practice:
- Is there any case where
createdwould be used overmounted? - What can I use the
createdevent for, in real-life (real-code) situation?
created() : since the processing of the options is finished you have access to reactive data properties and change them if you want. At this stage DOM has not been mounted or added yet. So you cannot do any DOM manipulation here
mounted(): called after the DOM has been mounted or rendered. Here you have access to the DOM elements and DOM manipulation can be performed for example get the innerHTML:
console.log(element.innerHTML)
So your questions:
Is there any case where created would be used over mounted?
Created is generally used for fetching data from backend API and setting it to data properties. But in SSR mounted() hook is not present you need to perform tasks like fetching data in created hook only
What can I use the created event for, in real-life (real-code) situation?
For fetching any initial required data to be rendered(like JSON) from external API and assigning it to any reactive data properties
data:{ myJson : null, errors: null }, created(){ //pseudo code database.get().then((res) => { this.myJson = res.data; }).catch((err) => { this.errors = err; }); }