#AD Top Online Web Development & Programming Courses | Udemy

Vue.js – Fetch & display data from an API

Last modified September 6th 2022 | #vue | GitHub Source Code [GitHub]

Displaying data from an API is common task in modern web development. In this tutorial we’ll be building a Vue.js component to fetch and display API data. By the end of this tutorial you’ll be able to display the current Bitcoin price from a third party API in a Vue.js application.

For this tutorial I created a project using create-vue.

With the project created the first thing we need to do is create a new FetchData.vue file in the /src/components folder. Once created we’ll start by adding the <template> tag. If you’re new to Vue.js this tag is simply a container for the HTML code you want to render:

<template> <div v-if="!data">Loading...</div> <pre v-else>{{ data }}</pre> </template>
Code language: HTML, XML (xml)

We’ll be adding to this later in the tutorial but for now it will allow us to display data from the API if the request is successful. We’ve used v-if to check if the data exists, if it doesn’t loading text is displayed and v-else to display the data and hide the loading text once the data has been fetched.

CoinDesk provides a free API that will allow us to fetch and display the current bitcoin price. Let’s now make our API request by adding the following script to the FetchData.vue file below the <template> section:

<script> export default { data() { return { data: null, }; }, methods: { async fetchData() { const response = await fetch("https://api.coindesk.com/v1/bpi/currentprice.json"); this.data = await response.json(); }, }, mounted() { this.fetchData(); }, }; </script>
Code language: HTML, XML (xml)

Let’s take a closer look at what is happening here. Vue calls the mounted() hook when the component is added to the DOM. This hook then calls the fetchData method which makes the API request and stores the response in the data object. The API request itself is using the vanilla JavaScript fetch() method.

We can now is load the component by modifying the App.vue file as follows:

<script setup> import FetchData from "./components/FetchData.vue"; </script> <template> <div class="wrapper"> <FetchData /> </div> </template>
Code language: HTML, XML (xml)

If you now run the npm run dev command you’ll see the data the API returns in your browser. Now we know that the API request is working let’s modify the <template> to display only the Bitcoin price in US dollars as follows:

<template> <div v-if="!data">Loading...</div> <p v-else>Current Bitcoin Price = USD${{ data.bpi.USD.rate }}</p> </template>
Code language: HTML, XML (xml)

That’s all for this tutorial. You should now have an understanding of how to fetch and display API data using Vue.js. Stay tuned as we’ll be adding many more Vue.js tutorials in the future. AS always the full source code can be found on GitHub.

#AD Shop Web Developer T-Shirts