Vue.js `mounted` Hook

In the development of Single File Components (SFC) with Vue.js, understanding the order of lifecycle hooks is crucial for writing maintainable and reactive code. Among them, the mounted hook is one of the most critical phases in the entire lifecycle; it marks the moment when the instance has been fully created and successfully mounted onto the DOM. Unlike the created hook, at this stage data binding and rendering logic are complete, allowing developers to perform operations that strictly depend on real DOM elements.
Once the Vue instance is initialized and the component is inserted into the page, the mounted lifecycle hook is triggered. This phase has the following significant characteristics:

  • DOM is Ready: At this point, the HTML structure of the component already exists in the browser and can be accessed and modified directly via DOM APIs (such as jQuery or Vue's provided $el).
  • Data Binding Complete: The rendering logic for all reactive data defined in the template has finished; you can see the final interface state presented to the user.
  • Ideal Timing for Asynchronous Operations: Since the component is fully loaded and visible to users, this is an excellent location to initiate network requests or perform other time-consuming operations, avoiding errors caused by the DOM not being ready.

Typical Application Scenarios and Code Examples

While the created hook is suitable for data initialization (such as calling APIs or setting timers), certain operations must be executed safely only after mounting. Below are several of the most common usage scenarios:

  1. Direct Access and Modification of the DOM
    When it is necessary to obtain specific attributes of an element or dynamically change its style, and these cannot be handled through Vue's directive system, mounted is the preferred location. For example, adjusting the size of a specific element after component loading to adapt to the screen layout.

  2. Initialization of Third-Party Libraries
    If you rely on external JavaScript libraries (such as Chart.js or Leaflet) to render charts or maps, these libraries typically require DOM elements to exist before they can correctly bind data sources.

  3. Preparation Before Listening for Window Size Changes
    When implementing responsive layouts, it is sometimes necessary to ensure the component is fully mounted before calculating viewport dimensions, in order to obtain accurate initial measurement values.

The following code example demonstrates how to perform DOM operations within the mounted hook:

export default {
  data() {
    return {
      counter: 0,
      elementHeight: null
    }
  },
  
  mounted() {
    // Get the height of the root element of the component and store it in a data property
    this.elementHeight = document.querySelector('.card').offsetHeight
    
    console.log(`Component is mounted, current height is: ${this.elementHeight}px`)

    // Simulate an asynchronous operation: initiate a request after the DOM is ready
    setTimeout(() => {
      fetch('/api/data')
        .then(response => response.json())
        .then(data => {
          this.counter = data.totalItems;
          console.log('Data loaded successfully, total count is:', this.counter);
        });
    }, 1000);
    
    // Note: Do not directly manipulate DOM properties (e.g., style.height) in mounted,
    // but rather prefer using Vue directives or computed properties to maintain reactivity.
    // This section is only for demonstration of how to retrieve the current value; 
    // in actual development, it is recommended to avoid breaking the reactivity chain.
  }
}

Comparative Analysis with Other Lifecycle Hooks

To more clearly locate the scope of action of mounted, we need to distinguish it from the two preceding and following key lifecycle hooks:

  • vs created: In the created phase, the component instance is created but has not yet been mounted to the DOM. Attempting to access $el or performing operations dependent on the DOM at this stage will throw an error. Therefore, any logic requiring real DOM interaction should be moved to mounted.

  • vs beforeUnmount / unmount: These are hooks added in Vue 3 (corresponding to beforeDestroy in Vue 2), used for cleaning up resources. In contrast, mounted focuses on operations at the "start" phase, while hooks during the unmount phase are responsible for preventing memory leaks and clearing side effects such as timers.

Best Practices and Precautions

Although mounted provides powerful functionality, the following principles should be followed in actual development to ensure code quality:

  • Prioritize Reactivity: Unless native DOM APIs (such as directly manipulating event listeners) must be used, avoid modifying DOM properties outside of templates to prevent breaking Vue's reactivity system.
  • Avoid Blocking the Main Thread: If mounted contains a large amount of synchronous computation or complex logic, it may cause page rendering lag. For time-consuming tasks, it is recommended to use asynchronous methods for delayed execution.
  • Unified Error Handling: Ensure that all network requests initiated within hooks have appropriate error handling mechanisms to prevent component state inconsistency due to network exceptions.

By reasonably using the mounted lifecycle hook, developers can build robust application architectures that conform to Vue.js's reactive philosophy while flexibly addressing complex DOM requirements. Mastering this concept is an important step towards deeply understanding the Vue.js ecosystem.