Using Vue.js with Axios to fetch and display data from an API is a common practice. Here’s a basic example to guide you through the process:
Step 1: Set Up Your Vue.js ApplicationMake sure you have Vue.js installed. If not, you can install it via CDN or Vue CLI.
Step 2: Install AxiosIf you haven’t already installed Axios, use npm or yarn to install it:
npm install axios
# or
yarn add axios
Step 3: Create Vue Component
Create a Vue component where you’ll fetch data using Axios.
<template>
<div>
<h1>Data from API:</h1>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
items: [], // To store fetched data
};
},
mounted() {
this.fetchData(); // Fetch data when the component mounts
},
methods: {
fetchData() {
const apiUrl = 'YOUR_API_ENDPOINT'; // Replace with your API endpoint
axios.get(apiUrl)
.then(response => {
this.items = response.data; // Update items with fetched data
})
.catch(error => {
console.error('Error fetching data:', error);
});
},
},
};
</script>
Replace 'YOUR_API_ENDPOINT'
with the actual URL of the API you want to fetch data from.
Include and mount your Vue component in the main Vue instance or wherever it’s appropriate in your application.
import Vue from 'vue';
import YourComponent from './YourComponent.vue'; // Replace with your component's path
new Vue({
el: '#app',
components: {
YourComponent,
},
template: '<YourComponent/>', // Render your component
});
Step 5: HTML Structure
In your HTML file, include the script tag to load Vue.js and your compiled JavaScript file. Ensure you have a <div id="app"> where your Vue instance will mount.
<!DOCTYPE html>
<html>
<head>
<!-- Your head content -->
</head>
<body>
<div id="app">
<!-- Your Vue component will render here -->
<your-component></your-component>
</div>
<script src="path/to/vue.js"></script>
<script src="path/to/your-compiled-js-file.js"></script>
</body>
</html>
Ensure you replace 'path/to/vue.js' and 'path/to/your-compiled-js-file.js'
with the correct paths.
This setup will fetch data from the API using Axios and display it in your Vue component. Adjust the structure and styles according to your application's needs.