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
Frontend Development Projects with Vue.js 3

You're reading from   Frontend Development Projects with Vue.js 3 Learn the fundamentals of building scalable web applications and dynamic user interfaces with Vue.js

Arrow left icon
Product type Paperback
Published in Mar 2023
Publisher Packt
ISBN-13 9781803234991
Length 628 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (4):
Arrow left icon
Hugo Di Francesco Hugo Di Francesco
Author Profile Icon Hugo Di Francesco
Hugo Di Francesco
Clifford Gurney Clifford Gurney
Author Profile Icon Clifford Gurney
Clifford Gurney
Raymond Camden Raymond Camden
Author Profile Icon Raymond Camden
Raymond Camden
Maya Shavin Maya Shavin
Author Profile Icon Maya Shavin
Maya Shavin
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Part 1: Introduction and Crash Course
2. Chapter 1: Starting Your First Vue Project FREE CHAPTER 3. Chapter 2: Working with Data 4. Chapter 3: Vite and Vue Devtools 5. Part 2: Building Your First Vue App
6. Chapter 4: Nesting Components (Modularity) 7. Chapter 5: The Composition API 8. Chapter 6: Global Component Composition 9. Chapter 7: Routing 10. Chapter 8: Animations and Transitions 11. Part 3: Global State Management
12. Chapter 9: The State of Vue State Management 13. Chapter 10: State Management with Pinia 14. Part 4: Testing and Application Deployment
15. Chapter 11: Unit Testing 16. Chapter 12: End-to-End Testing 17. Chapter 13: Deploying Your Code to the Web 18. Index 19. Other Books You May Enjoy

Exploring methods

In Vue 2.0, Vue defines component methods inside the methods object as part of a Vue instance. You compose each component method as a normal JavaScript function. The Vue method is scoped to your Vue component and can be run from anywhere inside the component it belongs to. It also has access to the this instance, which indicates the instance of the component:

<script>
  export default {
    methods: {
        myMethod() { console.log('my first method'); }
    }
  }
</script>

From Vue 3.0 onward, with <script setup>, as with local data, you can define a method as a regular function and it will work the same way as with the traditional approach. Hence, we can rewrite the preceding code as follows:

<script setup>
  const myMethod = () => { console.log('my first method'); }
</script>

You then can bind the methods to HTML events of an element as its event listeners in the template section. When binding events to HTML elements in Vue, you would use the @ symbol. For example, v-on:click is equivalent to @click, as shown in the following code block:

<template>
    <button id="click-me" v-on:click="myMethod">Click me
    </button>
    <button id="click-me" @click="myMethod">Click me
      shorter</button>
</template>

Clicking on both buttons triggers the same myMethod() method and generates the same result.

Let’s build a component with some methods.

Exercise 1.08 – triggering methods

In this exercise, we are going to build a component that uses Vue’s methods API. Consider how similarly these Vue methods can be written to 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 file for this exercise, refer to https://github.com/PacktPublishing/Frontend-Development-Projects-with-Vue.js-3/tree/v2-edition/Chapter01/Exercise1.08

We will build a list of different elements. For each element, we bind an onClick event with a component method, and alert users about the index of the clicked element 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.08 folder by using the following commands in order:
    > cd Chapter01/Exercise1.08/
    > 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-08.vue in the src/components directory.
  5. Inside Exercise1-08.vue, within the <script setup> section, let’s define a method, triggerAlert, that receives an index and displays an alert informing users which index has been clicked:
    <script setup>
    const triggerAlert = (index) => {
          alert(`${index} has been clicked`)
        }
    </script>
  6. In the template section, set up an anonymous v-for loop on an HTML list and add a button element inside the list element. Set the loop to iterate 5 times, and display the index value as each button’s label:
    <template>
      <div>
        <h1>Triggering Vue Methods</h1>
        <ul>
          <li v-for="index in 5":key="index">
            <button>Trigger {{index}}</button>
          </li>
        </ul>
      </div>
    </template>
  7. Add the @click directive, referencing the triggerAlert method, and pass the value of index as an argument:
    <template>
      <div>
        <h1>Triggering Vue Methods</h1>
        <ul>
          <li v-for="index in 5" :key="index">
            <button @click="triggerAlert(index)">Trigger
              {{ index }}</a>
          </li>
        </ul>
      </div>
    </template>
  8. Add a margin between each button for readability:
    <style>
    button {
      margin: 10px;
    }
    </style>
  9. 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.28 – Outputting a list of triggers

Figure 1.28 – Outputting a list of triggers

The following prompt is displayed when a trigger is clicked:

Figure 1.29 – Displaying a browser alert with the index number in it

Figure 1.29 – Displaying a browser alert with the index number in it

Note

While you can add an event listener to any HTML element, we suggest applying them to native HTML interactive elements such as anchor tags, form input, or buttons to help with browser accessibility.

At this point, you can utilize the Vue methods API to define and trigger methods from the HTML template, and parse arguments into each method dynamically. In the next exercise, we will explore how to return data with Vue methods within a Vue component.

Exercise 1.09 – returning data using Vue methods

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 we conditionally render these elements depending on whether our product is in stock or not.

To access the code file for this exercise, refer to https://github.com/PacktPublishing/Front-End-Development-Projects-with-Vue.js/tree/v2-edition/Chapter01/Exercise1.09.

We will build a list of different elements and demonstrate 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.09 folder by using the following commands in order:
    > cd Chapter01/Exercise1.09/
    > yarn
  2. Run the application using the following command:
    yarn dev
  3. Open the exercise project in your VS Code (by using the code . command within the project directory), or your preferred IDE.
  4. Create a new Vue component file named Exercise1-09.vue in the src/components directory.
  5. Inside Exercise1-09.vue, within the <script> section, we set up two data objects, totalItems and totalCost, which will be updated when a user clicks on our shop’s buttons:
    <script>
    export default {
      data(){
        return {
          totalCost: 0,
          totalItems: 0
        }
      }
    }
    </script>
  6. In the template section, we display the value of totalItems and totalCost accordingly:
    <template>
     <div>
       <h1>Returning Methods</h1>
       <div>Cart({{ totalItems }}) {{ totalCost }} </div>
     </div>
    </template>
  7. Within the script section, let’s create an addToCart method, which will update totalCost and totalItems for the current component based on the received number, n, by using this.totalCost and this.totalItems:
    <script>
    export default {
      data() {
        /*…*/
      },
      methods: {
        addToCart(n) {
          this.totalItems = this.totalItems + 1
          this.totalCost = this.totalCost + n
        },
      },
    }
    </script>
  8. Let’s iterate through a random amount to create buttons for adding a quantity to the cart. The quantity is the button’s index. Then, we bind the addToCart method to each button, with its index as the function’s input argument:
    <template>
      <div>
        <h1>Returning Methods</h1>
        <div>Cart({{ totalItems }}) {{ totalCost }} </div>
        <ul>
          <li v-for="n in 5" :key="n">
            <button @click="addToCart(n)">Add {{ n }}
              </button>
          </li>
        </ul>
      </div>
    </template>
  9. Add a 10px margin to the button element for readability:
    <style>
    button {
      margin: 10px;
    }
    </style>
  10. Go to https://localhost:3000 and the output is as follows:
Figure 1.30 – Pressing any of the buttons will demonstrate the cart logic

Figure 1.30 – Pressing any of the buttons will demonstrate the cart logic

When you click on the buttons, the totalItems counter should increment by 1, but totalCost will increment by the n value, which should demonstrate a normal cart functionality. For example, when clicking Add 2, then Add 5, the output will be as follows:

Figure 1.31 – Output displaying Returning Methods after increments of 2 and 5

Figure 1.31 – Output displaying Returning Methods after increments of 2 and 5

  1. Now, let’s format totalCost. Create a method called formatCurrency, which accepts one argument. We will return the same value after giving it two decimal points and a $ symbol:
    <script>
    export default {
      data() {
        /*…*/
      },
      methods: {
        addToCart(n) { /*…*/},
        formatCurrency(val) {
          return `$${val.toFixed(2)}`
        },
      },
    }
    </script>
  2. To use this method in the template, 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">
            <button @click="addToCart(n)">Add {{
              formatCurrency(n) }}</button>
          </li>
        </ul>
      </div>
    </template>

The following screenshot displays the output of the preceding code:

Figure 1.32 – All the values now are in currency format while retaining the cart counter

Figure 1.32 – All the values now are in currency format 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.

In the next section, we will explore a significant part of a component – the lifecycle and available component hooks in Vue.

You have been reading a chapter from
Frontend Development Projects with Vue.js 3 - Second Edition
Published in: Mar 2023
Publisher: Packt
ISBN-13: 9781803234991
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 €18.99/month. Cancel anytime