Understanding component lifecycle hooks
The Vue component lifecycle events happen during a component’s lifecycle, from creation to deletion. They allow us to add callbacks and side effects at each stage of the component’s life when necessary.
Vue executes the events in order, as follows:
setup
: This event runs before all other hooks, includingbeforeCreate
. It doesn’t have access to this instance since the instance has not yet been created at this point. It is mainly for using Composition API and is treated in the same way Vue treatsscript setup
. We will discuss this event more in Chapter 5, The Composition API.beforeCreate
: This runs when your component has been initialized.data
has not been made reactive and events are not set up in your DOM.created
: You will be able to access reactive data and events, but the templates and DOM are not mounted or rendered. This hook is generally good to use when requesting asynchronous data from a server since you will more than likely want this information as early as possible before the virtual DOM is mounted.beforeMount
: A very uncommon hook, as it runs directly before the first render of your component and is not called Server-Side Rendering.mounted
: Mounting hooks are among the most common hooks you will use since they allow you to access your DOM elements so that non-Vue libraries can be integrated.beforeUpdate
: This runs immediately after a change to your component occurs and before it has been re-rendered. It’s useful for acquiring the state of reactive data before it has been rendered.updated
: It runs immediately after thebeforeUpdate
hook and re-renders your component with new data changes.beforeUnMount
: This is fired directly before unmounting your component instance. The component will still be functional until theunmounted
hook is called, allowing you to stop event listeners and subscriptions to data to avoid memory leaks. Note this event is calledbeforeDestroy
in Vue 2.x.unmounted
: All the virtual DOM elements and event listeners have been cleaned up from your Vue instance. This hook allows you to communicate that to anyone or any element that needs to know this has been done. This event in Vue 2.x is calleddestroyed
.
Let’s do a small exercise to learn how and when to use Vue’s lifecycle hooks, and when they trigger.
Exercise 1.10 – using a Vue lifecycle to control data
In this exercise, we will be learning how and when to use Vue’s lifecycle hooks, and when they are triggered by using JavaScript alerts. By the end of the exercise, we will be able to understand and use multiple Vue lifecycle hooks.
To access the code file for this exercise, refer to https://github.com/PacktPublishing/Frontend-Development-Projects-with-Vue.js-3/tree/v2-edition/Chapter01/Exercise1.10.
We will build a list of different elements demonstrating adding different quantities to a cart. Then, we will display the updated cart’s total value in a currency format by performing the following:
- Use the application generated with
npm init vue@3
as a starting point, or within the root folder of the code repository, navigate into theChapter01/Exercise1.10
folder by using the following commands in order:> cd Chapter01/Exercise1.10/ > yarn
- Run the application using the following command:
yarn dev
- Open the exercise project in VS Code (by using the
code .
command within the project directory) or your preferred IDE. - Create a new Vue component file named
Exercise1-10.vue
in thesrc/components
directory. - Inside
Exercise1-10.vue
, we start by creating an array of data to iterate through in a list element, set the key ton
, and output the{{item}}
value inside of the<li>
element using curly braces:<template> <div> <h1>Vue Lifecycle hooks</h1> <ul> <li v-for="(item, n) in list" :key="n"> {{ item }} </li> </ul> </div> </template> <script> export default { data() { return { list: [ 'Apex Legends', 'A Plague Tale: Innocence', 'ART SQOOL', 'Baba Is You', 'Devil May Cry 5', 'The Division 2', 'Hypnospace Outlaw', 'Katana ZERO', ], } } } </script>
- Add
beforeCreated()
andcreated()
as properties below thedata()
function. Set an alert or console log inside these hooks so that you can see when they are being triggered:<script> export default { data(){ /*…*/ }, beforeCreate() { alert('beforeCreate: data is static, thats it') }, created() { alert('created: data and events ready, but no DOM') }, } </script>
- When you refresh your browser, you should see both alerts before you see your list load on the page:
Figure 1.33 – Observing the beforeCreate() hook alert first
- The following screenshot displays the
created()
hook alert after thebeforeCreate()
hook:
Figure 1.34 – Observing the before() hook alert after the beforeCreate() hook
- Define
beforeMount()
andmounted()
in the same way as in step 6. Set an alert or console log inside of these hooks so that you can see when they are being triggered:<script> export default { data() { /*…*/ }, /*…*/ beforeMount() { alert('beforeMount: $el not ready') }, mounted() { alert('mounted: DOM ready to use') }, } </script>
- When you refresh your browser, you should also see these alerts before you can see your list load on the page:
Figure 1.35 – Observing the beforeMount() hook alert after the create() hook
- The following screenshot displays the
mounted()
hook alert after thebeforeMount()
hook:
Figure 1.36 – Observing the mounted() hook alert after the beforeMount() hook
- Add a new
button
element inside your<li>
element that renders theitem
output. Use a@click
directive to bind this button to a method calleddeleteItem
and pass theitem
value as an argument:<template> <div> <h1>Vue Lifecycle hooks</h1> <ul> <li v-for="(item, n) in list" :key="n"> {{ item }} <button @click="deleteItem(item)">Delete</button> </li> </ul> </div> </template>
- Add a method called
deleteItem
into amethods
object above your hooks but below thedata()
function. Inside this function, passvalue
as an argument and filter out items from thelist
array based on this value. Then, replace the existing list with the new list:<script> export default { data() { /*…*/ }, /*…*/ methods: { deleteItem(value) { this.list = this.list.filter(item => item !== value) }, }, } </script>
- Add
beforeUpdate()
andupdated()
as functions same as in step 9 and set an alert or console log inside them:<script> export default { /*...*/ beforeUpdate() { alert('beforeUpdate: we know an update is about to happen, and have the data') }, updated() { alert('updated: virtual DOM will update after you click OK') }, } </script>
When you delete a list item by clicking on the Delete button in your browser, you should see these alerts. For example, when deleting the first item in the list, beforeUpdated
will trigger:
Figure 1.37 – BeforeCreated is called first after clicking on any delete button
Then, updated
triggers, as shown in the following screenshot:
Figure 1.38 – updated is called when the Vue engine finishes updating the component before rendering to the DOM
- Continue adding
beforeUnmount()
andunmounted()
to the component options as function properties. Set an alert or console log inside these hooks so that you can see when they are being triggered:<script> export default { /*...*/ beforeUnmount() { alert('beforeUnmount: about to blow up this component') }, unmounted() { alert('unmounted: this component has been destroyed') }, } </script>
- Add a new string to your
list
array – for example,testing
unmounted hooks
:<script> export default { data() { return { list: [ 'Apex Legends', 'A Plague Tale: Innocence', 'ART SQOOL', 'Baba Is You', 'Devil May Cry 5', 'The Division 2', 'Hypnospace Outlaw', 'Katana ZERO', 'testing unmounted hooks', ], } },
- You should see the unmount alerts according to this order:
beforeUnmount
–beforeCreated
–created
–beforeMount
–unmounted
–mounted
. An example output screen displaying the alert forbeforeUnmount
is shown here:
Figure 1.39 – Alert displays when a component is about to be unmounted
Note
mounted
and created
lifecycle hooks will run every time a component is initialized. If this is not the desired effect, consider running the code you want to run once from the parent component or view, such as the App.vue
file.
In this exercise, we learned what Vue lifecycle hooks are, when they trigger, and in what order they trigger. This will be useful in combination with triggering methods and controlling data within your Vue components.
Next, we will discuss how we style our Vue components using the <
style>
section.