Categories
Vue Answers

How to make async/await axios calls with Vue.js?

Spread the love

To make asynchronous Axios calls with async/await in Vue.js, we can use the axios library along with async and await keywords in our Vue component methods. Here’s an example of how to do it:

First, ensure we have Axios installed in your project:

npm install axios

Then, in our Vue component:

<template>
  <div>
    <button @click="fetchData">Fetch Data</button>
    <div v-if="loading">Loading...</div>
    <div v-if="error">Error: {{ error }}</div>
    <div v-if="data">
      <ul>
        <li v-for="item in data" :key="item.id">{{ item.title }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      data: null,
      loading: false,
      error: null
    };
  },
  methods: {
    async fetchData() {
      this.loading = true;
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        this.data = response.data;
      } catch (error) {
        this.error = error.message;
      }
      this.loading = false;
    }
  }
};
</script>

In this example we import Axios at the top of the script.

Then we define a method called fetchData, which is marked as async.

This method will make an asynchronous HTTP GET request using Axios.

Inside fetchData, we set loading to true to indicate that data is being fetched.

We use try and catch blocks to handle successful responses and errors respectively.

Inside the try block, we use await to asynchronously wait for the response from the Axios GET request.

Once the response is received, we store the response data in the data property.

If an error occurs during the request, it will be caught in the catch block, and we set the error property to the error message.

Finally, we set loading back to false after the request is completed.

Now, when we click the “Fetch Data” button, the fetchData method will be called, and data will be fetched asynchronously using Axios with async/await syntax.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *