Reader small image

You're reading from  Front-End Development Projects with Vue.js

Product typeBook
Published inNov 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838984823
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
Raymond Camden
Raymond Camden
author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

Clifford Gurney
Clifford Gurney
author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

Philip Kirkbride
Philip Kirkbride
author image
Philip Kirkbride

Philip Kirkbride has over 5 years of experience with JavaScript and is based in Montreal. He graduated from a technical college in 2011 and since then he has been working with web technologies in various roles.
Read more about Philip Kirkbride

Maya Shavin
Maya Shavin
author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

View More author details
Right arrow

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.

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Front-End Development Projects with Vue.js
Published in: Nov 2020Publisher: PacktISBN-13: 9781838984823

Authors (5)

author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

author image
Philip Kirkbride

Philip Kirkbride has over 5 years of experience with JavaScript and is based in Montreal. He graduated from a technical college in 2011 and since then he has been working with web technologies in various roles.
Read more about Philip Kirkbride

author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin