Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Frontend Development Projects with Vue.js 3

You're reading from   Frontend Development Projects with Vue.js 3 Learn the fundamentals of building scalable web applications and dynamic user interfaces with Vue.js

Arrow left icon
Product type Paperback
Published in Mar 2023
Publisher Packt
ISBN-13 9781803234991
Length 628 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (4):
Arrow left icon
Hugo Di Francesco Hugo Di Francesco
Author Profile Icon Hugo Di Francesco
Hugo Di Francesco
Clifford Gurney Clifford Gurney
Author Profile Icon Clifford Gurney
Clifford Gurney
Raymond Camden Raymond Camden
Author Profile Icon Raymond Camden
Raymond Camden
Maya Shavin Maya Shavin
Author Profile Icon Maya Shavin
Maya Shavin
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Part 1: Introduction and Crash Course
2. Chapter 1: Starting Your First Vue Project FREE CHAPTER 3. Chapter 2: Working with Data 4. Chapter 3: Vite and Vue Devtools 5. Part 2: Building Your First Vue App
6. Chapter 4: Nesting Components (Modularity) 7. Chapter 5: The Composition API 8. Chapter 6: Global Component Composition 9. Chapter 7: Routing 10. Chapter 8: Animations and Transitions 11. Part 3: Global State Management
12. Chapter 9: The State of Vue State Management 13. Chapter 10: State Management with Pinia 14. Part 4: Testing and Application Deployment
15. Chapter 11: Unit Testing 16. Chapter 12: End-to-End Testing 17. Chapter 13: Deploying Your Code to the Web 18. Index 19. Other Books You May Enjoy

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, including beforeCreate. 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 treats script 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 the beforeUpdate 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 the unmounted hook is called, allowing you to stop event listeners and subscriptions to data to avoid memory leaks. Note this event is called beforeDestroy 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 called destroyed.

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:

  1. Use the application generated with npm init vue@3 as a starting point, or within the root folder of the code repository, navigate into the Chapter01/Exercise1.10 folder by using the following commands in order:
    > cd Chapter01/Exercise1.10/
    > yarn
  2. Run the application using the following command:
    yarn dev
  3. Open the exercise project in VS Code (by using the code . command within the project directory) or your preferred IDE.
  4. Create a new Vue component file named Exercise1-10.vue in the src/components directory.
  5. Inside Exercise1-10.vue, we start by creating an array of data to iterate through in a list element, set the key to n, 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>
  6. Add beforeCreated() and created() as properties below the data() 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>
  7. 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

Figure 1.33 – Observing the beforeCreate() hook alert first

  1. The following screenshot displays the created() hook alert after the beforeCreate() hook:
Figure 1.34 – Observing the before() hook alert after the beforeCreate() hook

Figure 1.34 – Observing the before() hook alert after the beforeCreate() hook

  1. Define beforeMount() and mounted() 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>
  2. 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

Figure 1.35 – Observing the beforeMount() hook alert after the create() hook

  1. The following screenshot displays the mounted() hook alert after the beforeMount() hook:
Figure 1.36 – Observing the mounted() hook alert after the beforeMount() hook

Figure 1.36 – Observing the mounted() hook alert after the beforeMount() hook

  1. Add a new button element inside your <li> element that renders the item output. Use a @click directive to bind this button to a method called deleteItem and pass the item 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>
  2. Add a method called deleteItem into a methods object above your hooks but below the data() function. Inside this function, pass value as an argument and filter out items from the list 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>
  3. Add beforeUpdate() and updated() 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

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

Figure 1.38 – updated is called when the Vue engine finishes updating the component before rendering to the DOM

  1. Continue adding beforeUnmount() and unmounted() 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>
  2. 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',
          ],
        }
      },
  3. You should see the unmount alerts according to this order: beforeUnmountbeforeCreatedcreatedbeforeMountunmountedmounted. An example output screen displaying the alert for beforeUnmount is shown here:
Figure 1.39 – Alert displays when a component is about to be unmounted

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.

You have been reading a chapter from
Frontend Development Projects with Vue.js 3 - Second Edition
Published in: Mar 2023
Publisher: Packt
ISBN-13: 9781803234991
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime