Module: Vue Component Lifecycle

Use cases

Vue Component Lifecycle: Use Cases

The Vue Component Lifecycle is a series of events that a component goes through from its creation to its destruction. Understanding these events allows you to hook into specific moments to perform actions, making your components more dynamic and efficient. Here's a breakdown of common use cases for each lifecycle hook:


1. beforeCreate

  • Use Case: Limited. This is the very first hook, and the component instance hasn't been initialized yet. Data, methods, and computed properties are not available.
  • Example: Logging component creation for debugging purposes (though created is generally preferred).
  • Code Snippet:
    export default {
      beforeCreate() {
        console.log('Component is being created, but data is not yet available.');
      }
    }
    

2. created

  • Use Case: Ideal for initial data fetching, event bus setup, or setting up watchers that depend on reactive data. Data and methods are available, but the DOM hasn't been rendered yet.
  • Examples:
    • Fetching data from an API: Make an API call to populate initial data.
    • Setting up a WebSocket connection: Establish a connection to a real-time server.
    • Registering event listeners on a global event bus: Listen for events emitted from other components.
  • Code Snippet:
    export default {
      data() {
        return {
          items: []
        }
      },
      created() {
        // Simulate API call
        setTimeout(() => {
          this.items = [
            { id: 1, name: 'Item 1' },
            { id: 2, name: 'Item 2' }
          ];
        }, 1000);
      }
    }
    

3. beforeMount

  • Use Case: Perform final adjustments before the component is inserted into the DOM. Useful for manipulating the virtual DOM before it's rendered.
  • Example: Modifying the component's template based on some condition. (Less common than using computed properties or methods for this).
  • Code Snippet:
    export default {
      data() {
        return {
          showContent: false
        }
      },
      beforeMount() {
        // Example:  Conditionally show content based on a user role
        this.showContent = this.$store.state.user.role === 'admin';
      }
    }
    

4. mounted

  • Use Case: This is where you interact with the DOM. The component has been inserted into the DOM, and you can access DOM elements directly. This is the most commonly used hook for DOM manipulation.
  • Examples:
    • Focusing an input field: Set focus to an input element after the component is rendered.
    • Integrating with third-party libraries that require DOM access: Initialize a jQuery plugin or a charting library.
    • Setting up event listeners directly on DOM elements: Add event listeners that aren't handled by Vue's event handling system.
  • Code Snippet:
    export default {
      mounted() {
        const inputElement = this.$el.querySelector('input');
        if (inputElement) {
          inputElement.focus();
        }
      }
    }
    

5. beforeUpdate

  • Use Case: Called before the component's DOM is re-rendered due to data changes. Useful for performing actions before the DOM is updated, such as saving the previous state.
  • Example: Saving the previous DOM state for comparison after the update.
  • Code Snippet:
    export default {
      data() {
        return {
          previousValue: null
        }
      },
      beforeUpdate(oldVNode) {
        this.previousValue = oldVNode.elm.textContent; // Save previous text content
      }
    }
    

6. updated

  • Use Case: Called after the component's DOM has been re-rendered due to data changes. Use with caution, as it can lead to infinite loops if not handled carefully. Generally, avoid direct DOM manipulation here unless absolutely necessary.
  • Example: Triggering a third-party library that needs to be re-initialized after DOM updates. (Often better handled in mounted if possible).
  • Code Snippet:
    export default {
      updated() {
        // Be careful with DOM manipulation here!
        // Example: Re-initialize a library that depends on the updated DOM
        // this.$nextTick(() => {
        //   // Initialize library after DOM updates are complete
        // });
      }
    }
    

7. beforeUnmount (Vue 3) / beforeDestroy (Vue 2)

  • Use Case: Called before a component instance is unmounted. This is the place to clean up resources, such as timers, event listeners, or WebSocket connections.
  • Examples:
    • Clearing timers: clearInterval() or clearTimeout().
    • Removing event listeners: removeEventListener().
    • Closing WebSocket connections: socket.close().
    • Canceling pending requests: Abort any ongoing API calls.
  • Code Snippet:
    export default {
      data() {
        return {
          timerId: null
        }
      },
      mounted() {
        this.timerId = setInterval(() => {
          console.log('Timer running...');
        }, 1000);
      },
      beforeUnmount() { // Vue 3
        clearInterval(this.timerId);
        console.log('Component is being unmounted. Timer cleared.');
      }
    }
    

8. unmounted (Vue 3) / destroyed (Vue 2)

  • Use Case: Called after a component instance has been unmounted. This is the final cleanup step. The component is no longer in the DOM, and its data and methods are no longer accessible.
  • Example: Logging component destruction for debugging.
  • Code Snippet:
    export default {
      unmounted() { // Vue 3
        console.log('Component has been unmounted.');
      }
    }
    

Important Considerations:

  • $nextTick(): When performing DOM manipulation after data changes, use $nextTick() to ensure that the DOM has been updated before accessing it.
  • Avoid Infinite Loops: Be careful when using updated to avoid creating infinite loops by triggering further updates.
  • Vue 3 vs. Vue 2: Note the naming differences between Vue 3 (beforeUnmount, unmounted) and Vue 2 (beforeDestroy, destroyed).
  • Composition API: With the Composition API, you can use onBeforeMount, onMounted, etc., within the setup() function to achieve the same functionality.

This provides a comprehensive overview of Vue component lifecycle hooks and their common use cases. Remember to choose the appropriate hook based on the specific task you need to perform.