How to fetch data from an API with Vue.js and Axios?

To fetch data from an API using Vue.js and Axios, you can follow these steps:

  1. Install Axios:

    npm install axios
  2. Import Axios in your Vue component:

    import axios from 'axios';
  3. Create a data property in your component to store the fetched data:

    data() { return { fetchedData: [] } }
  4. Make an API request in a lifecycle hook (e.g., created or mounted) using Axios:

    created() { axios.get('https://api.example.com/data') .then(response => { this.fetchedData = response.data; }) .catch(error => { console.error(error); }); }

    In this example, we're making a GET request to an API endpoint, and in the response handler, we're setting the fetched data to the fetchedData property of the component.

  5. Display the fetched data in your template:

    <ul> <li v-for="item in fetchedData" :key="item.id"> {{ item.name }} </li> </ul>

    This is just an example of how you can display the fetched data. You can customize it based on the structure of your API response.

By following these steps, you will be able to fetch data from an API using Vue.js and Axios. Remember to handle any errors that may occur during the API request.