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.