Module: Vue Component Lifecycle

Mounted and updated hooks

Vue Component Lifecycle: Mounted and Updated Hooks

Mounted Hook

The mounted hook is called after the component has been mounted to the DOM. This means the component's template has been rendered, and it's now accessible in the browser. It's a great place to perform tasks that require access to the DOM, such as:

  • Fetching data: Initiate API calls to retrieve data needed for the component.
  • Setting up event listeners: Attach event listeners to DOM elements.
  • Integrating with third-party libraries: Initialize libraries that interact with the DOM (e.g., jQuery plugins, charting libraries).
  • Performing DOM manipulations: Directly manipulate the DOM if necessary (though generally discouraged in favor of Vue's reactivity).
  • Starting timers or animations: Begin timers or animations that rely on the component being in the DOM.

Example:

<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Loading...'
    };
  },
  mounted() {
    // Simulate fetching data from an API
    setTimeout(() => {
      this.message = 'Data loaded!';
    }, 1000);
  }
};
</script>

In this example, the mounted hook waits 1 second and then updates the message data property, causing the component to re-render with the new message. The initial "Loading..." message is displayed until the component is mounted and the setTimeout function executes.

Updated Hook

The updated hook is called after the component's DOM has been updated due to a reactive data change. This hook is called repeatedly whenever the component re-renders.

Important Considerations:

  • Avoid infinite loops: Be extremely careful when using updated. If you modify data within the updated hook that triggers another re-render, you can easily create an infinite loop.
  • Use with caution: Generally, you should avoid directly manipulating the DOM within the updated hook. Vue's reactivity system is designed to handle DOM updates efficiently.
  • Use cases: updated is less commonly used than mounted. Some valid use cases include:
    • Performing DOM measurements: If you need to measure the size or position of an element after it has been updated.
    • Integrating with third-party libraries that require updates: Some libraries might need to be notified when the component's DOM has changed.
    • Advanced animations: Triggering animations based on changes to the component's data.

Example:

<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0
    };
  },
  mounted() {
    console.log('Component mounted');
  },
  updated() {
    console.log('Component updated. Count:', this.count);
    // Example:  Log the height of the <p> element after each update
    console.log('Paragraph height:', document.querySelector('p').offsetHeight);
  },
  methods: {
    increment() {
      this.count++;
    }
  }
};
</script>

In this example, the updated hook logs a message to the console each time the count data property changes. It also demonstrates how to access the DOM element and get its height. Each click of the "Increment" button will trigger a re-render and call the updated hook.

Key Differences Summarized:

Feature Mounted Updated
When Called After the component is first attached to the DOM After the component's DOM is updated due to data changes
Frequency Once Multiple times (on every re-render)
Use Cases Initial setup, data fetching, DOM integration DOM measurements, advanced animations, specific third-party library updates
Caution None significant Avoid infinite loops, use sparingly