Vue.js Lifecycle Hooks: 'beforeMount' and 'mounted'

Vue.js, a progressive JavaScript framework, provides developers with a robust set of tools to manage the lifecycle of components. In this guide, we'll explore two essential Vue.js lifecycle hooks: 'beforeMount' and 'mounted'. These hooks play a crucial role in defining the behavior of components before and after they are added to the DOM (Document Object Model).

1. Enhancing User Experience with 'beforeMount'


'beforeMount' lifecycle hook

The 'beforeMount' hook offers developers a chance to intervene just before a Vue component is mounted, providing a valuable opportunity for pre-mount configurations. However, it comes with a caveat: attempting to access DOM elements within this hook is discouraged, as they are not accessible until after the component is mounted.

Example 1. Dynamic text change

Let's consider a scenario where we want to dynamically change the text content of a paragraph element before the component is mounted. In the following example from CompOne.vue, we attempt to modify the text inside a paragraph element with the id 'pEl' using this.$refs.pEl.innerHTML. However, this results in an error, emphasizing the limitation of accessing DOM elements before mounting.

<!-- CompOne.vue -->
<template>
  <h2>Component</h2>
  <p>This is the component</p>
  <p ref="pEl" id="pEl">We try to access this text from the 'beforeMount' hook.</p>
</template>

<script>
export default {
  beforeMount() {
    console.log("beforeMount: This is just before the component is mounted.");
    this.$refs.pEl.innerHTML = "Hello World!"; // <-- Does not work, DOM element not accessible
  }
}
</script>

Exercise 1: Customizing 'beforeMount'

Extend your understanding by creating a custom lifecycle hook called 'customBeforeMount' that triggers just before 'beforeMount'. Use this hook to log a message or perform any action before the actual mounting process begins.

2. Unveiling the 'mounted' hook

Once a component is successfully added to the DOM, the 'mounted' hook is invoked. This is the opportune moment to execute code that relies on DOM elements belonging to the component, utilizing features like the ref attribute and $refs object.

Example 2. Alert on mount

In this example from CompOne.vue, an alert popup appears right after the component is added to the DOM, demonstrating the immediate invocation of the 'mounted' hook.

<!-- CompOne.vue -->
<template>
  <h2>Component</h2>
  <p>Right after this component is added to the DOM, the mounted() function is called and we can add code to that mounted() function. In this example, an alert popup box appears after this component is mounted.</p>
  <p><strong>Note:</strong> The reason that the alert is visible before the component is visible is because the alert is called before the browser gets to render the component to the screen.</p>
</template>

<script>
export default {
  mounted() {
    alert("The component is mounted!");
  }
}
</script>

Example 3. Focusing on the input field

In a more practical scenario, the 'mounted' hook can be employed to enhance user experience. In CompOne.vue, the cursor is automatically placed inside an input field right after the component is mounted, allowing users to start typing without additional interaction.

<!-- CompOne.vue -->
<template>
  <h2>Form Component</h2>
  <p>When this component is added to the DOM tree, the mounted() function is called, and we put the cursor inside the input element.</p>
  <form @submit.prevent>
    <label>
      <p>
        Name: <br>
        <input type="text" ref="inpName">
      </p>
    </label>
    <label>
      <p>
        Age: <br>
        <input type="number">
      </p>
    </label>
    <button>Submit</button>
  </form>
  <p>(This form does not work, it is only here to show the mounted lifecycle hook.)</p>
</template>

<script>
export default {
  mounted() {
    this.$refs.inpName.focus();
  }
}
</script>

Exercise 2. Customizing 'mounted'

Extend the example by creating a custom lifecycle hook called 'customMounted' that triggers right after the 'mounted' hook. Implement a feature or log a message to demonstrate the utility of this custom hook.

In this exploration of Vue.js lifecycle hooks, we've delved into the intricacies of 'beforeMount' and 'mounted' hooks, pivotal stages in the lifecycle of Vue components. These hooks empower developers to orchestrate actions precisely before and after a component is added to the DOM, providing a nuanced control over the application's behavior. The examples showcased the nuances of the 'beforeMount' hook, cautioning against premature attempts to access DOM elements. Simultaneously, the 'mounted' hook demonstrated its power in executing actions immediately after a component became part of the DOM, opening avenues for dynamic interactions and enhanced user experiences.

As we navigated through practical scenarios, such as modifying text content before mounting and automatically focusing on an input field post-mount, the significance of these lifecycle hooks became evident. The exercises introduced opportunities for customization, allowing developers to create their custom hooks and explore further possibilities.