Component life cycle events

Friends, hello!

A practical understanding of component life cycle events enables you to quickly analyze and develop business problems. We will analyze 7 component life cycle events using the Composition API in the Vue3 framework as an example.

onBeforeMount()

The lifecycle event fires before the component appears in the DOM tree.

  • The first of all lifecycle events has access to reactive data.

  • The component has been created. The first rendering phase has not started. The component is not yet in the DOM tree.

Method signature

onBeforeMount(callback(): void): void

The execution of the callback function is synchronous. You can execute asynchronous code in a callback function. The Vue framework will not wait for asynchronous code to complete execution.

Example: Retrieving data from the server

We can request data from the server immediately after setting up the reactive state of the component in

// <script setup>
import {onBeforeMount} from "vue";
const width = ref(window.innerWidth)

const reszie = () => {
  width.value = window.innerWidth;
}

onBeforeMount(() => {
  window.addEventListener('resize', resize);
})

onMounted()

The lifecycle event fires after the component appears in the DOM tree.

  • A component is considered mounted if all child synchronous components are mounted.

  • The component is displayed in the DOM tree.

Method signature

onMounted(callback: () => void): void

The execution of the callback function is synchronous. You can execute asynchronous code in a callback function. The Vue framework will not wait for asynchronous code to complete execution.

Example: Initializing a Third Party Library

For example, let's take the chart display library Chart.js. This library requires a reference to a DOM element as input. The onMounted hook fires after the component template is rendered in the DOM tree. The chartRef reactive link will have a pointer to the canvas element.

// <script setup>
import {onMounted, ref} from "vue";
const canvasRef = ref<HTMLCanvasElement | null>(null)
const chartRef = shallowRef<ChartJS | null>(null)


onMounted(() => {
  chartRef.value = new ChartJS(canvasRef.value, config as any)
})
// template
<canvas ref="canvasRef"/>

Example: Retrieving data from an external source

If, after displaying the component, we need additional data from the server, then we use the onMounted() event.

// <script setup>
import {onMounted, ref} from "vue";

const users = ref<{id: number, name: string}[]>([]);

onMounted(async () => {
  const response = await fetch("http://localhost:3000/users");
  users.value = await response.json()
})
// template
<ul>
  <li v-for="user of users">{{user.name}}</li>
</ul>

Example: DOM event logging

We use onMounted when we need to track global events of our application in the component. It is important for us that our component is visible on the screen while creating the subscription.

// <script setup>
import {onMounted, ref} from "vue";
const width = ref(window.innerWidth)

const reszie = () => {
  width.value = window.innerWidth;
}

onMounted(() => {
  window.addEventListener('resize', resize)
})

onBeforeUpdate()

Fires before the DOM tree is updated. Used to interact with the DOM tree. It is safe to change the state of a component.

Method signature

onBeforeUpdate(callback: () => void): void

The execution of the callback function is synchronous. You can execute asynchronous code in a callback function. The Vue framework will not wait for asynchronous code to complete execution.

Example: Removing Component References

If we need to store an array of references to the template elements of our component, then when the number of elements changes, we need to update the reactive data. If we use ref with v-for in a component template, then there is no guarantee that the ref array will store the same sequence as the data in v-for. We need to manage the array of HTML elements ourselves.

// <script setup>
import {onBeforeUpdate, shallowRef} from "vue";
const liElements = shallowRef<(HTMLLIElement | undefined) []>([])

onBeforeUpdate(() => {
  liElements.value = []
})

const onUpdateRef = (e: any, index: number) => {
  liElements.value[index] = e
}
// template
<li v-for="(user, index) in users"
          :ref="e => onUpdateRef(e, index)"
          :key="user.id"
          tabindex="1"
          @click="onItemClick(user.id)">{{user.name}}</li>

onUpdated()

The callback function is triggered after the DOM of the component tree has changed in accordance with the reactive state of the component. Various state changes are combined into a single component render cycle to optimize performance.

Method signature

onMounted(callback: () => void): void

The execution of the callback function is synchronous. You can execute asynchronous code in a callback function. The Vue framework will not wait for asynchronous code to complete execution.

Example: getting the applied reactive state in the DOM tree.

The user clicks on the button, the component's reactive state changes and is applied to the DOM. The callback in the onUpdated method contains the same data in both the DOM and the reactive state.

// <script setup>
import {onUpdated, ref} from "vue";

const count = ref(0)
const divRef = ref<HTMLDivElement | null>(null)

onUpdated(() => {
  const divCountValue = parseInt(divRef.value.innerHTML)
  // divCountValue === count => true
  console.log(divCountValue === count.value)
})
// template
  <div ref="divRef">{{count}}</div>
  <button @click="count++">Count</button>

onBeforeUnmounted()

The call occurs until the component is deleted. The component's reactive states are active. Placing logic that will remove events or calculate memory usage is a good idea

Method signature

onBeforeUnmounted(callback: () => void): void

The execution of the callback function is synchronous. You can execute asynchronous code in a callback function. The Vue framework will not wait for asynchronous code to complete execution.

Example: deleting timers created in a component

Events and timers are registered in onBeforeMount or onMounted depending on the goals of the task. Clearing registered handlers is done in onBeforeUnmount.

// <script setup>
let intervalId;

onMounted(() => {
  intervalId = setInterval(() => {
    // logic here
  },1000)
})

onBeforeUnmount(() => {
  clearInterval(intervalId)
})

onUnmounted()

The component has been destroyed. All reactive states are stopped. We can interact with the created timer subscriptions, DOM or server connection.

Method signature

onUnmounted(callback: () => void): void

The execution of the callback function is synchronous. You can execute asynchronous code in a callback function. The Vue framework will not wait for asynchronous code to complete execution.

Usage example

Removing the window change event handler.

// <script setup>
import {onMounted, onUnmounted, ref} from "vue";
const size = ref({width: window.innerWidth, height: window.innerHeight})

const resize = () => {
  size.value.width = window.innerWidth
  size.value.height = window.innerHeight
}

onMounted(() => {
  window.addEventListener('resize', resize)
})

onUnmounted(() => {
  window.removeEventListener('resize', resize)
})

onErrorCaptured()

The method provides the ability to intercept errors in the component. Code errors in

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *