Vue.js is a popular JavaScript framework for building user interfaces. It’s designed to be incrementally adoptable. It can also work with other libraries and existing projects. However, Vue can power sophisticated single-page applications by itself (with the help of modern tooling and supporting libraries, of course). Vue, being a JavaScript-based framework, supports all the JavaScript features as well. JSON is a popular JavaScript data format used for data management. Many APIs also expose data in JSON format.
In this guide, we will demonstrate building a single-page web app using Vue. It will report the latest exchange values for some of the most popular cryptocurrencies: Bitcoin and Ethereum. The exchange rates will be pulled from CryptoCompare API. To make the API request and handle the return data, we will also incorporate Axios into our code.
Prerequisites
The following conditions need to be fulfilled before diving into the guide.
- A Linux machine running Ubuntu First, check out how to set up your own Ubuntu cloud machine on CloudSigma.
- A text editor with support for syntax highlighting, for example, Atom, Sublime Text, Visual Studio Code, etc.
- Familiarity with HTML and JavaScript. You can learn more about integrating JavaScript with HTML here.
- Familiarity with the JSON data format. It’s a popular data format that originated from JavaScript. Learn more about working with JSON in JavaScript here.
- Familiarity with API requests. Check out CloudSigma API to incorporate it in your own scripts and applications.
Step 1: Create the Application Framework
For easier management of the project files, we will create a dedicated directory. We called it cloudsigma-vue-demo:
1 |
mkdir -pv cloudsigma-vue-demo/ |
First, create a new file index.html:
1 |
touch index.html |
Then, open the file in a text editor and enter the following code:
1 2 3 4 5 6 7 8 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Crypto Pricing</title> </head> <body></body> </html> |
Integrate Foundation and Vue.js. Note that the positionings of the codes are important:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Crypto Pricing</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.7.4/css/foundation.min.css" integrity="sha512-TgmH0v8FUwmsr3yDgd5PTCgR6lRZ2Q5c7KsUNTHcoxZpOExCX16MYECIL4xdRQOhQlz7pCnZlmA4zda58QWxBw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> </head> <body> <script src="https://unpkg.com/vue@3"></script> </body> </html> |
Here:
- The link to the Foundation CSS code goes to the header. Check out Foundation on cdnjs.
- The link to the Vue JavaScript code goes within the <body> . For ease of use, we’ve put it at the bottom. Check out Vue on cdnjs.
We’ll use a separate JavaScript file vueApp.js to manage our Vue app code. Add the file to our HTML file:
1 2 |
<script src="https://unpkg.com/vue@3"></script> <script src="vueApp.js"></script> |
Step 2: Create a Basic Vue App
For demonstration, we’re going to create a simple app that prints the latest exchange value of two of the most popular cryptocurrencies Bitcoin and Ethereum into USD and EUR. Because the price of cryptocurrencies is volatile, we’ll use CryptoCompare API to grab the latest exchange price. Check out CryptoCompare API.
- Basic Markup
Enter the following code in the <body> of index.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<div class="container" id="app"> <h3 class="text-center">Cryptocurrency Pricing</h3> <div class="columns medium-4"> <div class="card"> <div class="card-section"> <p> BTC in USD </p> </div> <div class="card-divider"> <p>{{ BTCtoUSD }}</p> </div> </div> </div> </div> |
Next, save the file and open index.html in the browser:
As you can see, we created a simple layout that will print the info of our cryptocurrency exchange rates. For now, we’ll work with a single cryptocurrency Bitcoin (BTC).
Did you notice the element {{ BTCtoUSD }}? In Vue, the double curly braces indicate a Vue object. When run, Vue will render those parts of the markup with data according to the instruction. We’re using {{ BTCtoUSD }} as a placeholder for the data that Vue.js will provide.
- Implement Vue.js Logic
Now, switch to vueApp.js. Here, we’ll tell Vue what data to deliver to the element {{ BTCtoUSD }}. Create a simple Vue application:
1 2 3 4 5 6 7 |
Vue.createApp({ data() { return { BTCtoUSD: 40000 } } }).mount('#app') |
Here, we’ve set a sample value for BTCtoUSD to 40000. This is mock data. We will implement the API later on for live values.
Open index.html in the browser. Notice any difference?
Vue swapped {{ BTCtoUSD }} to 40000.
Step 3: Iterate over Data with Vue
So far, we’ve implemented a static entry for a single cryptocurrency. What if you want to have multiple cryptocurrencies? Let’s try it out. Add another entry to show the exchange rate of BTC to EUR:
1 2 3 4 5 6 7 8 |
<div class="card"> <div class="card-section"> <p> BTC in EURO </p> </div> <div class="card-divider"> <p>{{ BTCinEUR }}</p> </div> </div> |
After that, update vueApp.js with the value for {{ BTCtoEUR }}:
1 2 3 4 5 6 7 8 |
Vue.createApp({ data() { return { BTCinUSD: 40000, BTCinEUR: 35000 } } }).mount('#app') |
Run the app in the browser:
This is all well and good. But what if you want to add exchange rates for more cryptocurrencies? Adding all of them one by one in index.html sounds impractical. In that case, we can let Vue handle the job. We will instruct Vue to iterate over each item and show it on the webpage.
To do so, we need to update the data of vueApp.js first. Include all the values in a single object cryptoDataValues:
1 2 3 4 5 6 7 8 9 10 |
Vue.createApp({ data() { return { cryptoDataValues: { "BTC": {"USD": 40000, "EUR": 35000}, "ETH": {"USD": 2700, "EUR": 2400} } } } }).mount('#app') |
Time to update index.html. Here, we will use the v-for tag to iterate over the dataset we defined:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<div class="columns medium-4" v-for="(result, index) in cryptoDataValues"> <div class="card"> <div class="card-section"> <p> {{ index }} </p> </div> <div class="card-divider"> <p>$ {{ result.USD }}</p> </div> <div class="card-section"> <p> € {{ result.EUR }}</p> </div> </div> </div> |
Run the app on the web browser:
Using this technique, we now only need to update the dataset of vueApp.js. Let’s try it out. Add a new random entry on the dataset:
1 2 3 4 5 6 7 8 9 10 11 |
Vue.createApp({ data() { return { cryptoDataValues: { "BTC": {"USD": 40000, "EUR": 35000}, "ETH": {"USD": 2700, "EUR": 2400}, "RANDOM": {"USD": 1234, "EUR": 5678} } } } }).mount('#app') |
Voila! It’s iterating through all the entries!
Step 4: Get Data from the API
It’s finally time we started working with the API. So far, we’ve been using mock data to establish the framework of our application. Now, we will feed live data to our app, thanks to CryptoCompare API.
To get the live data from the API, we’ll use the following URL:
1 |
https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR |
The API returns a JSON object that we can parse. To see what the API response is, use curl to request to the API:
1 |
curl 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR' |
The output looks almost like the hard-coded mock data we’re using, right? All we have to do now is switch out the data. We’ll use the mounted() function from Vue and GET function from the Axios library to fetch the data and store it in the variable results. Once the Vue app is mounted, the mounted() function is called. After successful mounting, the API call is made and the result is recorded. It will also notify changes to the webpage.
We need the Axios library to make it work. Add the Axios library from cdnjs:
1 2 3 4 5 6 7 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.31/vue.global.min.js" integrity="sha512-C/bodwN49fOc1z+jln+2l9FlJ+lZ8HifB30oLE87zMQwsfoWv6Ed25b/x646tlcKb7515VJrJK8uo1oIH1UR2Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="vueApp.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.26.0/axios.min.js" integrity="sha512-bPh3uwgU5qEMipS/VOmRqynnMXGGSRv+72H/N260MQeXZIK4PG48401Bsby9Nq5P5fz7hy5UGNmC/W1Z51h2GQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> |
Now, head over to the vueApp.js file and modify it so that it works with the API request and parses the data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const url = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR"; const app = Vue.createApp({ data() { return{ results: null } }, mounted() { axios .get(url) .then(response => { this.results = response.data }) } }).mount('#app') |
Here, the initial value of results is null because when loading the app for the first time, the browser expects a value. After Axios fetches the API output and updates the value, Vue automatically refreshes the webpage, thanks to its Hot Reload feature.
Verify the changes in the web browser. Note that it may take a couple of seconds to update the webpage with values, so you need to be patient.
Complete Codes
This guide was pretty long, so in this section, we have included the final code for both index.html and vueApp.js.
Here’s the code for index.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Crypto Pricing</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.7.4/css/foundation.min.css" integrity="sha512-TgmH0v8FUwmsr3yDgd5PTCgR6lRZ2Q5c7KsUNTHcoxZpOExCX16MYECIL4xdRQOhQlz7pCnZlmA4zda58QWxBw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> </head> <body> <div class="container" id="app"> <h3 class="text-center">Cryptocurrency Pricing</h3> <div class="columns medium-4" v-for="(result, index) in results"> <div class="card"> <div class="card-section"> <p> {{ index }} </p> </div> <div class="card-divider"> <p>$ {{ result.USD }}</p> </div> <div class="card-section"> <p> € {{ result.EUR }}</p> </div> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.31/vue.global.min.js" integrity="sha512-C/bodwN49fOc1z+jln+2l9FlJ+lZ8HifB30oLE87zMQwsfoWv6Ed25b/x646tlcKb7515VJrJK8uo1oIH1UR2Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.26.0/axios.min.js" integrity="sha512-bPh3uwgU5qEMipS/VOmRqynnMXGGSRv+72H/N260MQeXZIK4PG48401Bsby9Nq5P5fz7hy5UGNmC/W1Z51h2GQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="vueApp.js"></script> </body> </html> |
Here’s the code for vueApp.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const url = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR"; const app = Vue.createApp({ data() { return{ results: null } }, mounted() { axios .get(url) .then(response => { this.results = response.data }) } }).mount('#app') |
Final Thoughts
In this guide, we’ve demonstrated creating an API-consuming web app using only three tools:
- js
- Axios
- CryptoCompare API
We also showcased displaying data on a webpage, iterating over results, and replacing static data with dynamic ones (results from the API).
Now that you understand the fundamentals, feel free to modify the code and explore by yourself. You can add additional functions to the application, for example, displaying additional currencies. You can also implement the experience gained from this project to work with a different API.
Happy Computing!
- How to Deploy WordPress with Persistent Volume on Kubernetes Cluster - March 17, 2023
- Deploying Applications on Kubernetes Using Argo CD and GitOps - October 26, 2022
- Using Node.js Modules with npm and package.json: A Tutorial - October 6, 2022
- Using Ansible to Install and Configure WordPress with LAMP on Ubuntu - September 23, 2022
- Creating Views in the Django Web Application Framework - September 22, 2022