0
0
VueHow-ToBeginner · 4 min read

How to Use Axios in Vue: Simple Guide with Examples

To use axios in Vue, first install it with npm install axios. Then import axios in your component and call it inside lifecycle hooks or methods to fetch data asynchronously.
📐

Syntax

Here is the basic syntax to use axios in a Vue component:

  • import axios from 'axios': brings axios into your file.
  • axios.get(url): sends a GET request to the URL.
  • .then(response => { ... }): handles the successful response.
  • .catch(error => { ... }): handles errors if the request fails.
javascript
import axios from 'axios';

export default {
  data() {
    return {
      info: null,
      error: null
    };
  },
  mounted() {
    axios.get('https://api.example.com/data')
      .then(response => {
        this.info = response.data;
      })
      .catch(error => {
        this.error = error.message;
      });
  }
};
💻

Example

This example shows a Vue component that fetches user data from a public API when the component loads and displays it.

vue
<template>
  <div>
    <h2>User Info</h2>
    <div v-if="error" style="color: red">Error: {{ error }}</div>
    <div v-else-if="user">
      <p><strong>Name:</strong> {{ user.name }}</p>
      <p><strong>Email:</strong> {{ user.email }}</p>
    </div>
    <div v-else>Loading...</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: null,
      error: null
    };
  },
  async mounted() {
    try {
      const response = await axios.get('https://jsonplaceholder.typicode.com/users/1');
      this.user = response.data;
    } catch (err) {
      this.error = err.message;
    }
  }
};
</script>
Output
User Info Name: Leanne Graham Email: Sincere@april.biz
⚠️

Common Pitfalls

Common mistakes when using axios in Vue include:

  • Not importing axios before using it.
  • Forgetting to handle errors with .catch or try/catch.
  • Using this incorrectly inside promises without arrow functions.
  • Not waiting for the data before rendering, causing undefined errors.

Always use arrow functions or async/await to keep this context correct.

javascript
/* Wrong: Using regular function loses 'this' context */
axios.get(url).then(function(response) {
  this.data = response.data; // 'this' is undefined here
});

/* Right: Use arrow function to keep 'this' */
axios.get(url).then(response => {
  this.data = response.data;
});
📊

Quick Reference

Remember these tips when using axios in Vue:

  • Install axios with npm install axios.
  • Import axios in your component with import axios from 'axios'.
  • Use async/await or .then/.catch to handle requests.
  • Always handle errors to avoid app crashes.
  • Use lifecycle hooks like mounted() to fetch data after component loads.

Key Takeaways

Install and import axios before using it in Vue components.
Use async/await or arrow functions to keep the correct this context.
Always handle errors to prevent your app from breaking.
Fetch data in lifecycle hooks like mounted() for best results.
Display loading states to improve user experience while waiting for data.