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

Iterating over Objects

When requesting data from an API, you will often be iterating over an array of objects that contains both logic and raw content. Vue makes it easy to control the data's various states through its directive syntax. Conditional directives control the display state of DOM elements in Vue. The HTML syntax provides clear visibility when it comes to the display rules set in your component.

Exercise 1.09: Using a v-for Loop over an Array of Objects and Using Their Properties for v-if Conditions

In this exercise, we will be controlling a Vue data array and iterating over the objects inside of it.

To access the code files for this exercise, refer to https://packt.live/32YokKa.

  1. Open a command-line terminal, navigate into the Exercise1.09 folder, and run the following commands in order:
    > cd Exercise1.09/
    > code .
    > yarn
    > yarn serve

    Go to https://localhost:8080.

  2. Compose the following syntax inside Exercise1-09.vue and create a data object that contains a title string, and a favorite array of strings. We will loop over the interests object similarly to the array of strings; however, you will need to refer to the title key inside the interests object:
    <template>
      <div>
        <h1>Looping through array of objects</h1>
        <ul>
          <li v-for="(item, n) in interests" :key="n">
            {{ item.title }}
          </li>
        </ul>
      </div>
    </template>

    The output of the preceding code will be as follows:

    Figure 1.28: You should see a list of titles now in the frontend

    Figure 1.28: You should see a list of titles now in the frontend

  3. Let's create a second v-for loop to iterate over your favorites list. Note that we use different keys— fav and m—for our nested loop. This is because you can still use the values item and n inside the nested loop context:
    <template>
      <div>
        <h1>Looping through array of objects</h1>
        <ul>
          <li v-for="(item, n) in interests" :key="n">
            {{ item.title }}
            <ol>
              <li v-for="(fav, m) in item.favorite" :key="m">            {{ fav }}</li>
            </ol>
          </li>
        </ul>
      </div>
    </template>

    Figure 1.29 displays an output where looping is performed through an array of objects:

    Figure 1.29: Nested ordered list detailing your favorites

    Figure 1.29: Nested ordered list detailing your favorites

  4. To optimize the DOM tree, we can use the v-if conditional directive from Exercise 1.09 to hide unnecessary DOM elements:
    Figure 1.30: Displaying empty DOM elements in your virtual DOM

    Figure 1.30: Displaying empty DOM elements in your virtual DOM

  5. We will check whether there are more than 0 items in the array to display the ordered list HTML element. Add a v-if directive to the <ol> with the condition item.favorite.length > 0:
    // src/components/Exercise1-09.vue
    <template>
      <div>
        <h1>Looping through array of objects</h1>
        <ul>
          <li v-for="(item, n) in interests" :key="n">
            {{ item.title }}
            <ol v-if="item.favorite.length > 0">
              <li v-for="(fav, m) in item.favorite" :key="m">            {{ fav }}</li>
            </ol>
          </li>
        </ul>
      </div>
    </template>

    This won't make a difference in the visuals of your page, but when you inspect the virtual DOM tree in your browser, you'll notice an HTML comment in dev mode allowing you to understand where a v-if statement might be false. When you build for production, these HTML comments won't be in your DOM.

    Figure 1.31: Output displaying no HTML comment in production builds

Figure 1.31: Output displaying no HTML comment in production builds

By using the v-if directive in dev mode, you will see an HTML comment. These will not exist in production builds.

In this exercise we have been able to iterate over complex arrays of objects, outputting these objects' nested keys and controlling the view state of DOM elements based on length conditions.

Methods in Vue

Vue methods are defined inside the methods object within the Vue instance and can be written like normal JavaScript functions where you define a piece of logic that is executed. When you use JavaScript functions, normally, you would either return a value or simply perform a global action. The primary difference between writing functions and Vue methods is that the Vue method is scoped to your Vue component and can be run from anywhere inside the component it was written inside. Since the methods are scoped to your component's Vue instance, you can reference them inside of event directives easily in the HTML template. When binding events to HTML elements in Vue, you would use the @ symbol; for example, v-on:click is equivalent to @click.

Exercise 1.10: Triggering Methods

In this exercise, we are going to build a component that uses Vue's methods API. Consider how similar these Vue methods can be written like your own named functions in JavaScript, as they behave in a very similar way. By the end of the exercise, we should be able to use methods and trigger them from the HTML template.

To access the code files for this exercise, refer to https://packt.live/3kMTWs5.

  1. Open a command-line terminal and navigate into the Exercise1.10 folder and run the following commands in order:
    > cd Exercise1.10/
    > code .
    > yarn
    > yarn serve

    Go to https://localhost:8080.

  2. Let's loop over a method trigger and pass its number to a method. Set up an anonymous v-for loop on an HTML list and add an anchor element inside of the list element. Set the loop to iterate 5 times:
    <template>
      <div>
        <h1>Triggering Vue Methods</h1>
        <ul>
          <li v-for="n in 5" :key="n">
            <a href="#">Trigger</a>
          </li>
        </ul>
      </div>
    </template>
  3. Add the @click directive referencing a method called triggerAlert and pass the value of n as an argument. Output the value n into the anchor element using curly braces:
    <template>
      <div>
        <h1>Triggering Vue Methods</h1>
        <ul>
          <li v-for="n in 5" :key="n">
            <a href="#" @click="triggerAlert(n)">Trigger {{ n }}</a>
          </li>
        </ul>
      </div>
    </template>
  4. Inside the methods object, add the triggerAlert(n) key with the n argument. Inside this method, add an alert function, which will output the value n plus some static text:
    <script>
    export default {
      methods: {
        triggerAlert(n) {
          alert(`${n} has been clicked`)
        },
      },
    }
    </script>
  5. Add styling inside the <style> tag at the bottom of the component, and set the lang attribute to scss:

    Exercise1-10.vue

    22 <style lang="scss" scoped>
    23 ul {
    24   padding-left: 0;
    25 }
    26 li {
    27   display: block;
    28   list-style: none;
    29 
    30   + li {
    31     margin-top: 10px;
    32   }
    33 }
    34 
    35 a {
    36   display: inline-block;
    37   background: #4fc08d;
    38   border-radius: 10px;
    39   color: white;
    40   padding: 10px 20px;
    41   text-decoration: none;
    42 }
    43 </style>
  6. Your page should feature a list of buttons that when clicked, trigger an alert with a message that contains the button number you clicked as follows:
    Figure 1.32: Output a list of triggers

Figure 1.32: Output a list of triggers

The following prompt is displayed when a trigger is clicked:

Figure 1.33: Displaying a browser alert with the index number in it

Figure 1.33: Displaying a browser alert with the index number in it

Note

While you can add an event directive to any HTML element, a suggestion would be applying them to native HTML interactive elements such as anchor tags, form input, or buttons to help with browser accessibility.

In this exercise, we were able to utilize the Vue methods API to define and trigger methods from the HTML template, and parse arguments into each method dynamically.

Exercise 1.11: Returning Data Using Vue Methods

In this exercise, we are going to learn how to use Vue methods as a function to return data in the Vue instance and inside of the template.

Often in a web application, we want elements to appear on the page depending on whether a condition is met or not. For instance, if our product is not in stock, our page should display the fact that it is out of stock.

So, let's figure out how could we conditionally render these elements, depending on whether our product is in stock or not.

To access the code files for this exercise, refer to https://packt.live/3pHWCeh.

  1. Open a command-line terminal, navigate into the Exercise1.11 folder, and run the following commands in order:
    > cd Exercise1.11/
    > code .
    > yarn
    > yarn serve

    Go to https://localhost:8080.

  2. Let's iterate over a random amount and trigger an addToCart method. Set up two data objects, totalItems and totalCost, which will be updated when a user clicks on our shop buttons. Next, refer to data objects inside the script block of Vue by specifying this. For example, in the template block, we refer to totalItems as {{ totalItems }}, but in the script block, we will refer to it as this.totalItems. The same pattern is used for methods where addToCart would be referred to as this.addToCart within another method:
    <template>
      <div>
        <h1>Returning Methods</h1>
        <div>Cart({{ totalItems }}) {{ totalCost }} </div>
        <ul>
          <li v-for="n in 5" :key="n">
            <a href="#" @click="addToCart(n)">Add {{ n }}</a>
          </li>
        </ul>
      </div>
    </template>
    <script>
    export default {
      data() {
        return {
          totalItems: 0,
          totalCost: 0,
        }
      },
      methods: {
        addToCart(n) {
          this.totalItems = this.totalItems + 1
          this.totalCost = this.totalCost + n
        },
      },
    }
    </script>
    <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);
      border-radius: 10px;
      color: white;
      padding: 10px 20px;
      text-decoration: none;
    }
    </style>

    This will generate an output as follows:

    Figure 1.34: Pressing any of the buttons will demonstrate the cart logic

    Figure 1.34: Pressing any of the buttons will demonstrate the cart logic

    When you click the buttons, the items counter should increment by 1, but the cost will increment by the n value, which should demonstrate normal cart functionality (clicking Add 2, then Add 5):

    Figure 1.35: Output displaying Returning Methods after increments

    Figure 1.35: Output displaying Returning Methods after increments

  3. Let's talk money. We can use methods to perform logical operations that augment or format strings based on events. Create a method called formatCurrency, which accepts one argument. We will return the same value after giving it two decimal points and a $ symbol. To use this method in the template, simply add it to the interpolated curly braces and pass the value that was there as an argument inside the method instead:
    <template>
      <div>
        <h1>Returning Methods</h1>
        <div>Cart({{ totalItems }}) {{ formatCurrency(totalCost) }}      </div>
        <ul>
          <li v-for="n in 5" :key="n">
            <a href="#" @click="addToCart(n)">Add           {{ formatCurrency(n) }}</a>
          </li>
        </ul>
      </div>
    </template>
    <script>
    export default {
      data() {
        return {
          totalItems: 0,
          totalCost: 0,
        }
      },
      methods: {
        addToCart(n) {
          this.totalItems = this.totalItems + 1
          this.totalCost = this.totalCost + n
        },
        formatCurrency(val) {
          return `$${val.toFixed(2)}`
        },
      },
    }
    </script>

    The following screenshot displays the output of the preceding code:

    Figure 1.36: Now all the values are expected to look like currency, 
while retaining the cart counter

Figure 1.36: Now all the values are expected to look like currency, while retaining the cart counter

In this exercise, we were able to utilize Vue's methods API to parse arguments into methods, return modified values, and use methods to update the local data state in a life-like scenario.

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