Vue 3 - Fetch Data from an API
Tutorial built with Vue 3.2.45
Below is a quick example of how to fetch JSON data from an API in Vue 3 using the fetch()
function which comes built into all modern browsers.
Fetch Data with Vue 3
This sends an HTTP GET request to the Test JSON API, a fake online REST API that includes a /products
route that returns an array of products, each with an id
and name
property.
After the JSON data is fetched from the API it is rendered as a list with the Vue v-for
directive.
<script setup>
import { ref } from 'vue';
const products = ref(null);
fetch('https://testapi.jasonwatmore.com/products')
.then(response => response.json())
.then(data => products.value = data);
</script>
<template>
<div class="card m-3">
<h5 class="card-header text-center">Vue 3 fetch data from API</h5>
<div class="card-body">
<div v-if="products">
<h5>Products</h5>
<ul class="mb-0">
<li v-for="product in products" :key="product.id">{{product.name}}</li>
</ul>
</div>
<div v-if="!products" class="text-center">
<div class="spinner-border spinner-border-sm"></div>
</div>
</div>
</div>
</template>
Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/vue-3-fetch-data-from-api)
More Vue 3 HTTP Examples
For more examples of how to fetch data from an API with Vue 3 see Vue 3 - HTTP GET Request Examples.
Need Some Vue 3 Help?
Search fiverr for freelance Vue 3 developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!