Fetching and Displaying Data in Vue

Tutorial 2 of 5

1. Introduction

In this tutorial, you will learn how to fetch and display data from an API in a Vue.js application. APIs are data sources that allow us to retrieve information and use it in our applications. We will use two popular methods to fetch data - Fetch API and Axios.

By the end of this tutorial, you will be able to:
- Fetch data from an API using Fetch API and Axios.
- Display the fetched data in your Vue.js application.

This tutorial assumes you have basic knowledge of Vue.js and JavaScript. Familiarity with ES6 syntax, promises, and async/await would be beneficial.

2. Step-by-Step Guide

Fetching data from an API involves sending a request to the API endpoint and processing the response. Both Fetch API and Axios are promise-based, meaning they handle requests and responses asynchronously.

Fetch API is built into most modern browsers, while Axios is a standalone library that offers more powerful features, such as progress bars, automatic request retries, and response timeout.

Here are some best practices:
- Always handle API errors.
- Use async/await for cleaner code.
- Always sanitize and validate data before using it.

3. Code Examples

Let's start with a simple Vue component that fetches data from an API.

Fetch API

<template>
  <div>
    <div v-for="post in posts" :key="post.id">
      <h2>{{ post.title }}</h2>
      <p>{{ post.body }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      posts: []
    };
  },
  async created() {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    this.posts = await response.json();
  }
};
</script>

In the above code:
- We define a posts array in our data.
- When the component is created (created() lifecycle hook), we fetch data from the API.
- We use fetch() to send a GET request to the API.
- We use await to wait for the promise to resolve before assigning the response to posts.

Axios

<template>
  <div>
    <div v-for="post in posts" :key="post.id">
      <h2>{{ post.title }}</h2>
      <p>{{ post.body }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      posts: []
    };
  },
  async created() {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    this.posts = response.data;
  }
};
</script>

In the Axios example:
- We import the axios module.
- We use axios.get() to send a GET request to the API.
- Axios automatically transforms the JSON response into an object, so we can directly assign the response data to posts.

4. Summary

You've learned how to fetch data from an API in a Vue.js application using both Fetch API and Axios, and how to display that data in your components.

Next, you could explore more about handling API errors, displaying loading indicators, and pagination.

Additional resources:
- Vue.js Guide
- Using Fetch
- Axios GitHub

5. Practice Exercises

  1. Fetch data from the API 'https://jsonplaceholder.typicode.com/users' and display the users' names and email addresses.
  2. Add error handling to the Fetch API and Axios examples.
  3. Fetch data from two different APIs and display the combined results.

Tips:
- Always check if the data is available before trying to access its properties.
- You can use .catch() to handle errors in promises.
- To fetch data from two APIs, you can use Promise.all().