Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Front-End Development Projects with Vue.js
  • Table Of Contents Toc
Front-End Development Projects with Vue.js

Front-End Development Projects with Vue.js

By : Raymond Camden, Hugo Di Francesco, Clifford Gurney , Philip Kirkbride , Maya Shavin , Dániel Szabó
4.8 (10)
close
close
Front-End Development Projects with Vue.js

Front-End Development Projects with Vue.js

4.8 (10)
By: Raymond Camden, Hugo Di Francesco, Clifford Gurney , Philip Kirkbride , Maya Shavin , Dániel Szabó

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)
close
close
Preface

Async Methods and Data Fetching

Asynchronous functions in JavaScript are defined by the async function syntax and return an AsyncFunction object. These functions operate asynchronously via the event loop, using an implicit promise, which is an object that may return a result in the future. Vue.js uses this JavaScript behavior to allow you to declare asynchronous blocks of code inside methods by including the async keyword in front of a method. You can then chain then() and catch() functions or try the {} syntax inside these Vue methods and return the results.

Axios is a popular JavaScript library that allows you to make external requests for data using Node.js. It has wide browser support making it a versatile library when doing HTTP or API requests. We will be using this library in the next exercise.

Exercise 2.06: Using Asynchronous Methods to Retrieve Data from an API

In this exercise, you will asynchronously fetch data from an external API source and display it in the frontend using computed props.

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

  1. Open a command-line terminal, navigate to the Exercise 2.06 folder, and run the following commands to install axios:
    > cd Exercise2.06/
    > code .
    > yarn
    > yarn add axios
    > yarn serve

    Go to https://localhost:8080.

  2. Let's start by importing axios into our component and creating a method called getApi(). Use axios to call a response from https://api.adviceslip.com/advice and console.log the result. Include a button that has a click event bound to the getApi() call:
    <template>
      <div class="container">
        <h1>Async fetch</h1>
        <button @click="getApi()">Learn something profound</button>
      </div>
    </template>
    <script>
    import axios from 'axios'
    export default {
      methods: {
        async getApi() {
          return   axios.get('https://api.adviceslip.com/advice').        then((response) => {
            console.log(response)
          })
        },
      },
    }
    </script>
     
    <style lang="scss" scoped>
    .container {
      margin: 0 auto;
      padding: 30px;
      max-width: 600px;
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
    }
    blockquote {
      position: relative;
      width: 100%;
      margin: 50px auto;
      padding: 1.2em 30px 1.2em 30px;
      background: #ededed;
      border-left: 8px solid #78c0a8;
      font-size: 24px;
      color: #555555;
      line-height: 1.6;
    }
    </style>

    The output of the preceding code will be as follows:

    Figure 2.12: Screen displaying a very large object in the console

    Figure 2.12: Screen displaying a very large object in the console

  3. We are only interested in the data object inside the response object. Assign this data object to a Vue data prop called response that we can reuse:
    export default {
      data() {
        return {
          axiosResponse: {},
        }
      },
      methods: {
        async getApi() {
          return axios.get('https://api.adviceslip.com/advice').        then(response => {
            this.axiosResponse = response.data
          })
        },
      },
    }
  4. Output the quote from inside the response prop object using a computed prop that will update every time the response prop changes. Use a ternary operator to perform a conditional statement to check whether the response prop contains the slip object to avoid errors:
    <template>
      <div class="container">
        <h1>Async fetch</h1>
        <button @click="getApi()">Learn something profound</button>
        <blockquote v-if="quote">{{ quote }}</blockquote>
      </div>
    </template>
    <script>
    import axios from 'axios'
    export default {
      data() {
        return {
          axiosResponse: {},
        }
      },
      computed: {
        quote() {
          return this.axiosResponse && this.axiosResponse.slip
            ? this.axiosResponse.slip.advice
            : null
        },
      },
      methods: {
        async getApi() {
          return axios.get('https://api.adviceslip.com/advice').        then(response => {
            this.axiosResponse = response.data
          })
        },
      },
    }
    </script>

    Figure 2.13 displays the output generated by the preceding code:

    Figure 2.13: Screen displaying the quote output in your template

    Figure 2.13: Screen displaying the quote output in your template

  5. As a final touch, include a loading data prop so the user can see when the UI is loading. Set loading to false by default. Inside the getApi method, set loading to true, and in the then() chain, set it back to false after 4 seconds using the setTimeout function. You can use a ternary operator to change the button text between the loading state and its default state:
    <template>
      <div class="container">
        <h1>Async fetch</h1>
        <button @click="getApi()">{{
          loading ? 'Loading...' : 'Learn something profound'
        }}</button>
        <blockquote v-if="quote">{{ quote }}</blockquote>
      </div>
    </template>
    <script>
    import axios from 'axios'
    export default {
      data() {
        return {
          loading: false,
          axiosResponse: {},
        }
      },
      computed: {
        quote() {
          return this.axiosResponse && this.axiosResponse.slip
            ? this.axiosResponse.slip.advice
            : null
        },
      },
      methods: {
        async getApi() {
          this.loading = true
          return axios.get('https://api.adviceslip.com/advice').        then(response => {
            this.axiosResponse = response.data
            
            setTimeout(() => {
              this.loading = false
            }, 4000);
          })
        },
      },
    }
    </script>

The output of the preceding code will be as follows:

Figure 2.14: Screen displaying the loading button state output in your template

Figure 2.14: Screen displaying the loading button state output in your template

In this exercise, we saw how we can fetch data from an external source, assign it to a computed prop, display it in our template, and apply a loading state to our content.

Activity 2.01: Creating a Blog List Using the Contentful API

In this activity, we will build a blog that lists articles from an API source. This will test your knowledge of Vue by using all the basic functions of a Single-File Component (SFC) and async methods to fetch remote data from an API and use computed properties to organize deep nested object structures.

Contentful is a headless content management system (CMS) that allows you to manage content separately to your code repository. You can consume this content using the API inside as many code repositories as you need. For example, you may have a blog website that acts as a primary source of information, but your clients want a standalone page on a different domain that only pulls in the most recent featured articles. Using a headless CMS inherently allows you to develop these two separate code bases and use the same updated data source.

This activity will be using the headless CMS Contentful. The access keys and endpoints will be listed in the solution.

The following steps will help you complete the activity:

  1. Use the Vue CLI to create a new project that uses babel presets.
  2. Install the contentful dependency into your project.
  3. Use computed properties to output the deeply nested data from the API response.
  4. Use data props to output the user's name, job title, and description.
  5. Use SCSS to style the page.

The expected outcome is as follows:

Figure 2.15: Expected outcome with Contentful blog posts

Figure 2.15: Expected outcome with Contentful blog posts

Note

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

After the activity has been completed, you should be able to use async methods to pull remote data from an API source into your Vue components. You will find that computed props are a sophisticated way of breaking down the information into smaller chunks of reusable data.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Front-End Development Projects with Vue.js
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon