Book Image

Frontend Development Projects with Vue.js 3 - Second Edition

By : Maya Shavin, Raymond Camden, Clifford Gurney, Hugo Di Francesco
5 (2)
Book Image

Frontend Development Projects with Vue.js 3 - Second Edition

5 (2)
By: Maya Shavin, Raymond Camden, Clifford Gurney, Hugo Di Francesco

Overview of this book

Are you looking to use Vue.js 3 for building web apps but don't know where to begin? Frontend Development Projects with Vue.js 3 will help you get to grips with the core concepts of this JavaScript framework using practical examples that simulate real-world web projects. With this updated edition, you’ll experience all aspects of the new and improved Vue.js 3 as you work on mini projects such as a chat interface, a shopping cart, a price calculator, a to-do app, and a profile card generator for storing contact details. These realistic projects are presented as bite-size exercises that you can enjoy even as you challenge yourself. Throughout the book, you'll discover how to manage data in Vue components, define communication interfaces between components, and handle static and dynamic routing to control application flow. You'll also work with Vite and Vue DevTools and learn how to handle transition and animation effects for an engaging user experience. Finally, you’ll see how to test your app and deploy it to the web. By the end of this Vue.js book, you'll have the skills that enable you to work like an experienced Vue developer to build professional apps that can be used by others and have the confidence to tackle real-world frontend web development problems.
Table of Contents (20 chapters)
1
Part 1: Introduction and Crash Course
5
Part 2: Building Your First Vue App
11
Part 3: Global State Management
14
Part 4: Testing and Application Deployment

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.