Vue Lifecycle Hooks
The Vue component lifecycle events include the following:
beforeCreate
: 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 you can 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 in 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 non-Vue libraries can be integrated.beforeUpdate
: Runs immediately after a change to your component occurs, and before it has been re-rendered. Useful for acquiring the state of reactive data before it has been rendered.updated
: Runs immediately after thebeforeUpdate
hook and re-renders your component with new data changes.beforeDestroy
: Fired directly before destroying your component instance. The component will still be functional until the destroyed hook is called, allowing you to stop event listeners and subscriptions to data to avoid memory leaks.destroyed
: 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 was completed.
Exercise 1.12: Using Vue Lifecycles for Controlling Data
In this exercise, we will be learning how and when to use Vue's lifecycle hooks, and when they trigger 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 files for this exercise, refer to https://packt.live/36N42nT.
- Open a command-line terminal, navigate into the
Exercise1.12
folder, and run the following commands in order:> cd Exercise1.12/ > code . > yarn > yarn serve
Go to
https://localhost:8080
.Note
Feel free to swap the alert for
console.log()
. - Start by creating an array of data to iterate over in a list element, set the key to
n
, and output the value{{item}}
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 functions 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 { Â Â Â ... Â Â 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 can see your list load on the page:
The following screenshot displays the
created()
hook alert after thebeforeCreate()
hook: - Add
beforeMount()
andmounted()
as functions below thecreated()
hook. Set an alert or console log inside of these hooks so you can see when they are being triggered:<script> export default { ... Â Â 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:
The following screenshot displays the
mounted()
hook alert after thebeforeMount()
hook: - Add a new anchor element inside your
<li>
element that sits next to the item 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 }} <a @click="deleteItem(item)">Delete</a> Â Â Â Â Â Â </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 the list array that do not match the value, then replace the existing list with the new list:Exercise1-12.vue
17Â <script> 18Â export default { 19Â Â Â data() { 20Â Â Â Â Â return { 21Â Â Â Â Â Â Â list: [ 22Â Â Â Â Â Â Â Â Â 'Apex Legends', 23Â Â Â Â Â Â Â Â Â 'A Plague Tale: Innocence', 24Â Â Â Â Â Â Â Â Â 'ART SQOOL', 25Â Â Â Â Â Â Â Â Â 'Baba Is You', 26Â Â Â Â Â Â Â Â Â 'Devil May Cry 5', 27Â Â Â Â Â Â Â Â Â 'The Division 2', 28Â Â Â Â Â Â Â Â Â 'Hypnospace Outlaw', 29Â Â Â Â Â Â Â Â Â 'Katana ZERO', 30Â Â Â Â Â Â Â ], 31Â Â Â Â Â } 32Â Â Â }, 33Â Â Â methods: { 34Â Â Â Â Â deleteItem(value) { 35Â Â Â Â Â Â Â this.list = this.list.filter(item => item !== value) 36Â Â Â Â Â }, 37Â Â Â },
The complete code for this step is available at https://packt.live/3pJGLvO.
- Add styling inside the
<style>
tag at the bottom of the component, and set thelang
attribute toscss
:<style lang="scss" scoped> ul { Â Â padding-left: 0; } li { Â Â display: block; Â Â list-style: none; Â Â + li { Â Â Â Â margin-top: 10px; Â Â } } a { Â Â display: inline-block; Â Â background: rgb(235, 50, 50); Â Â padding: 5px 10px; Â Â border-radius: 10px; Â Â font-size: 10px; Â Â color: white; Â Â text-transform: uppercase; Â Â text-decoration: none; } </style>
- Add
beforeUpdate()
andupdated()
as functions below themounted()
hook and set an alert or console log inside these hooks so that you can see when they are being triggered:<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 the delete button in your browser, you should see these alerts.
- Add
beforeDestroy()
anddestroyed()
as functions below theupdated()
hook. Set an alert or console log inside these hooks so that you can see when they are being triggered:<script> export default { Â Â Â ... Â Â beforeDestroy() { Â Â Â Â alert('beforeDestroy: about to blow up this component') Â Â }, Â Â destroyed() { Â Â Â Â alert('destroyed: this component has been destroyed') Â Â }, } </script>
- Add a new item to your
list
array:<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',              ],     }   },
You should also see the destroy alerts after the update alerts are shown in your browser after you have saved this change with localhost running. This will generate the following output:
- Alerts will run at each lifecycle hook. Try deleting elements, adding new ones in the list array, and refreshing the page to see when each of these hooks occurs. This will generate an output as follows:
An alert will trigger every time you manipulate something on the page, demonstrating each available Vue lifecycle.
Note
Mounted
and created
lifecycle hooks will run every time a component loads. 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 and when they trigger. This will be useful in combination with triggering methods and controlling data within your Vue components.
Activity 1.01: Building a Dynamic Shopping List App Using Vue.js
In this activity, we will build a dynamic shopping list app that will test your knowledge of Vue by using all the basic functions of an SFC, such as expressions, loops, two-way binding, and event handling.
This application should let users create and delete individual list items and clear the total list in one click.
The following steps will help you complete the activity:
- Build an interactive form in one component using an input bound to
v-model
. - Add one input field that you can add shopping list items to. Allow users to add items by using the Enter key by binding a method to the
@keyup.enter
event. - Users can expect to clear the list by deleting all the items or removing them one at a time. To do so, you can use a
delete
method that can pass the array position as an argument, or simply overwrite the whole shopping list data prop to be an empty array[]
.The expected outcome is as follows:
Note
The solution for this activity can be found via this link.