Book Image

Front-End Development Projects with Vue.js

By : Raymond Camden, Hugo Di Francesco, Clifford Gurney, Philip Kirkbride, Maya Shavin
Book Image

Front-End Development Projects with Vue.js

By: Raymond Camden, Hugo Di Francesco, Clifford Gurney, Philip Kirkbride, Maya Shavin

Overview of this book

Are you looking to use Vue 2 for web applications, but don't know where to begin? Front-End Development Projects with Vue.js will help build your development toolkit and get ready to tackle real-world web projects. You'll get to grips with the core concepts of this JavaScript framework with practical examples and activities. Through the use-cases in this book, you'll discover how to handle data in Vue components, define communication interfaces between components, and handle static and dynamic routing to control application flow. You'll get to grips with Vue CLI and Vue DevTools, and learn how to handle transition and animation effects to create an engaging user experience. In chapters on testing and deploying to the web, you'll gain the skills to start working like an experienced Vue developer and build professional apps that can be used by other people. You'll work on realistic projects that are presented as bitesize exercises and activities, allowing you to challenge yourself in an enjoyable and attainable way. These mini projects include a chat interface, a shopping cart and price calculator, a to-do app, and a profile card generator for storing contact details. By the end of this book, you'll have the confidence to handle any web development project and tackle real-world front-end development problems.
Table of Contents (16 chapters)
Preface

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 the beforeUpdate 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.

  1. 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().

  2. 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>
  3. Add beforeCreated() and created() as functions 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 {
       ...
      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:

    Figure 1.37: Observe the beforeCreate() hook alert first

    Figure 1.37: Observe the beforeCreate() hook alert first

    The following screenshot displays the created() hook alert after the beforeCreate() hook:

    Figure 1.38: Observe the before() hook alert after the beforeCreate() hook

    Figure 1.38: Observe the before() hook alert after the beforeCreate() hook

  4. Add beforeMount() and mounted() as functions below the created() 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:

    Figure 1.39: Observe the beforeMount() hook alert after the create() hook

    Figure 1.39: Observe the beforeMount() hook alert after the create() hook

    The following screenshot displays the mounted() hook alert after the beforeMount() hook:

    Figure 1.40: Observe alert mounted() hook alert after the beforeMount() hook

    Figure 1.40: Observe alert mounted() hook alert after the beforeMount() hook

  5. 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 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 }} <a @click="deleteItem(item)">Delete</a>
          </li>
        </ul>
      </div>
    </template>
  6. 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 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   },
  7. Add styling inside the <style> tag at the bottom of the component, and set the lang attribute to scss:
    <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>
  8. Add beforeUpdate() and updated() as functions below the mounted() 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.

  9. Add beforeDestroy() and destroyed() as functions below the updated() 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>
  10. 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:

    Figure 1.41: Output displaying Vue Lifecycle hooks

    Figure 1.41: Output displaying Vue Lifecycle hooks

  11. 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:
    Figure 1.42: Displaying a message on every trigger

Figure 1.42: Displaying a message on every trigger

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:

  1. Build an interactive form in one component using an input bound to v-model.
  2. 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.
  3. 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:

    Figure 1.43: Final output

Figure 1.43: Final output

Note

The solution for this activity can be found via this link.