vue fetch data from api code example
Example 1: axios in vue
//Install Axios
npm install axios
//Import Axios in .vue file
import axios from 'axios'
//Add a method to implement Axios
testMethod () {
axios.post('URL')
.then(function (response) {
alert (response.data);
})
.catch(function (error) {
alert(error);
});
}
Example 2: vue fetch api
async created() {
// GET request using fetch with async/await
const response = await fetch("https://api.npms.io/v2/search?q=vue");
const data = await response.json();
this.totalVuePackages = data.total;
}
Example 3: how to use axios in vue
//Install Axios from terminal
npm install axios
//Import Axios in your HelloWorld.vue
import axios from 'axios'
//Add a method to implement Axios
test () {
axios.post('URL')
.then(function (response) {
alert (response.data);
})
.catch(function (error) {
alert(error);
});
}
Example 4: data fetching vue
<template>
<div>
<h1>{{ title }}</h1>
<ul>
<li v-for="user in users" :key="user.id">{{ user.id }}. {{ user.name }} - {{ user.email }}</li>
</ul>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Users',
props: {
title: String
},
data: () => ({
users: []
}),
mounted() {
axios.get('https://jsonplaceholder.typicode.com/users').then((res) => {
this.users = res.data
})
}
}
</script>
<style scoped>
h1 {
color: black;
font-size: 24px;
font-weight: 200;
padding: 0px 10px 0px;
}
ul li {
list-style: none;
color: black;
font-weight: 400;
opacity: 0.8;
font-size: 18px;
}
</style>
Example 5: vuejs list items from axios
<ul>
<li v-for="food in foods">
<h2>{{food.name}}</h2>
<ul>
<li v-for="nutrient in food.nutrients">{{nutrient.nutrient_id}}</li>
</ul>
</li>
</ul>
axios.get(url).then(response => {
this.foods = response.data.report.foods
})
Example 6: how to use api url in vue
<a :href="post.url" target="_blank"><img :src="post.image_url"></a>