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
Front-End Development Projects with Vue.js

You're reading from   Front-End Development Projects with Vue.js Learn to build scalable web applications and dynamic user interfaces with Vue 2

Arrow left icon
Product type Paperback
Published in Nov 2020
Publisher Packt
ISBN-13 9781838984823
Length 774 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (5):
Arrow left icon
Clifford Gurney Clifford Gurney
Author Profile Icon Clifford Gurney
Clifford Gurney
Philip Kirkbride Philip Kirkbride
Author Profile Icon Philip Kirkbride
Philip Kirkbride
Raymond Camden Raymond Camden
Author Profile Icon Raymond Camden
Raymond Camden
Maya Shavin Maya Shavin
Author Profile Icon Maya Shavin
Maya Shavin
Hugo Di Francesco Hugo Di Francesco
Author Profile Icon Hugo Di Francesco
Hugo Di Francesco
+1 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface
1. Starting Your First Vue Project 2. Working with Data FREE CHAPTER 3. Vue CLI 4. Nesting Components (Modularity) 5. Global Component Composition 6. Routing 7. Animations and Transitions 8. The State of Vue.js State Management 9. Working with Vuex – State, Getters, Actions, and Mutations 10. Working with Vuex – Fetching Remote Data 11. Working with Vuex – Organizing Larger Stores 12. Unit Testing 13. End-to-End Testing 14. Deploying Your Code to the Web Appendix

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 chapter is locked
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