How to Use Vue.js and Axios to Display Data from an API | DevsDay.ru

IT-блоги How to Use Vue.js and Axios to Display Data from an API

DigitalOcean Community Tutorials 1 августа 2022 г. rkoli


### Introduction [Vue.js](https://vuejs.org/guide/introduction.html#what-is-vue) is a front-end JavaScript framework for building user interfaces. It's designed from the ground up to be incrementally adoptable, and it integrates well with other libraries or existing projects. This approach makes it a good fit for small projects as well as sophisticated single-page applications when used with other tooling and libraries. An API, or Application Programming Interface, is a software intermediary that allows two applications to talk to each other. An API often exposes data that other developers can consume in their own apps, without worrying about databases or differences in programming languages. Developers frequently fetch data from an API that returns data in the JSON format, which they integrate into front-end applications. Vue.js is a great fit for consuming these kinds of APIs. In this tutorial, you'll create a Vue application that uses the [Cryptocompare API](https://www.cryptocompare.com/api/) to display the current prices of two leading cryptocurrencies: Bitcoin and Ethereum. In addition to Vue, you'll use the [Axios library](https://github.com/axios/axios/blob/master/README.md) to make API requests and process the obtained results. Axios is a great fit because it automatically transforms JSON data into JavaScript objects, and it supports [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises), leading to code that's easier to read and debug. And to make things look nice, we'll use the [Foundation](https://foundation.zurb.com/) CSS framework. <$>[note] **Note**: The Cryptocompare API is licensed for non-commercial use only. See their [licensing terms](https://www.cryptocompare.com/api/#introduction) if you wish to use it in a commercial project. <$> ## Prerequisites Before you begin this tutorial, you'll need the following: * A text editor that supports JavaScript syntax highlighting, such as [Atom](http://atom.io), [Visual Studio Code](https://code.visualstudio.com/), or [Sublime Text](https://www.sublimetext.com/). These editors are available on Windows, macOS, and Linux. * Familiarity with using HTML and JavaScript together. Learn more in [How To Add JavaScript to HTML](https://www.digitalocean.com/community/tutorials/how-to-add-javascript-to-html). * Familiarity with the JSON data format, which you can learn more about in [How to Work with JSON in JavaScript](https://www.digitalocean.com/community/tutorials/how-to-work-with-json-in-javascript). * Familiarity with making requests to APIs. For a comprehensive tutorial on working with APIs, take a look at [How to Use Web APIs in Python3](https://www.digitalocean.com/community/tutorials/how-to-use-web-apis-in-python-3). While it's written for Python, it will still help you understand the core concepts of working with APIs. ## Step 1 — Creating a Basic Vue Application In this step, you'll create a basic Vue application. We'll build a single HTML page with some mocked-up data that we will eventually replace with live data from the API. We'll use Vue.js to display this mocked data. For this first step, we'll keep all of the code in a single file. Create a new file called `index.html` using your text editor. In this file, add the following HTML markup, which defines an HTML skeleton and pulls in the Foundation CSS framework and the Vue.js library from content delivery networks (CDNs). By using a CDN, there's no additional code you need to download to start building your app. ```html [label index.html] Cryptocurrency Pricing Application

Cryptocurrency Pricing

BTC in USD

{{ BTCinUSD }}

``` The line `{{ BTCinUSD }}` is a placeholder for the data that Vue.js will provide, which is how Vue lets us declaratively render data in the UI. Let's define that data. Right below the ` ... ``` This code creates a new Vue app instance and attaches the instance to the element with the `id` of `app`. Vue calls this process *mounting* an application. We define a new Vue instance and configure it by passing a configuration [object](https://www.digitalocean.com/community/tutorials/understanding-objects-in-javascript). To the `createApp` instance, we pass a data object that returns the value of `BTCinUSD`. Further, we have invoked the `mount` method of the `createApp` instance with argument `#app` that specifies the `id` of the element we want to mount this application on and a [`data`](https://vuejs.org/api/options-state.html#data) option containing the data we want available to the view. In this example, our data model contains a single key-value pair that holds a mock value for the price of Bitcoin: `{ BTCinUSD: 3759.91}`. This data will be displayed on our HTML page, or our *view*, in the place where we enclosed the key in double curly braces like this: ```html [label index.html]

{{ BTCinUSD }}

``` We'll eventually replace this hard-coded value with live data from the API. Open this file in your browser. You'll see the following output on your screen, which displays the mock data: ![Vue app showing mock data for the bitcoin price in US Dollars](https://assets.digitalocean.com/articles/vuejs_api_cryptocurrency/NyjwbIM.png) We're displaying the price in U.S. dollars. To display it in an additional currency, like Euros, we'll add another key-value pair in our data model and add another column in the markup. First, add the line for Euros to the data model: ```html [label index.html] ``` Then replace the existing `
` section with the following lines. ```html [label index.html]

Cryptocurrency Pricing

BTC in USD

{{ BTCinUSD }}

BTC in EURO

{{ BTCinEURO }}

``` Now save the file and reload it in your browser. The app now displays the price of Bitcoin both in Euros as well as in US Dollars. ![Vue app with mock price of Bitcoin in both USD and Euros](https://assets.digitalocean.com/articles/vuejs_api_cryptocurrency/jTDUE3m.png) In this step, you created your Vue app with some sample data to ensure it loads. We've done all the work in a single file so far, so now we'll split things into separate files to improve maintainability. ## Step 2 — Separating JavaScript and HTML for Clarity To learn how things work, we placed all of the code in a single file. In this step, you'll separate the application code into two separate files: `index.html` and `vueApp.js`. The `index.html` file will handle the markup, and the JavaScript file will contain the application logic. We'll keep both files in the same directory. First, modify the `index.html` file and remove the JavaScript code, replacing it with a link to the `vueApp.js` file. Locate this section of the file: ```html [label index.html] ... ... ``` And modify it so it looks like this: ```html [label index.html] ... <^><^> ... ``` Then create the `vueApp.js` file in the same directory as the `index.html` file. In this new file, place the same JavaScript code that was originally in the `index.html` file, without the ` <^><^> ... ``` Save the file, then open `vueApp.js`. Modify and update `vueApp.js` so it makes a request to the API and fills the data model with the results. ```javascript [label vueApp.js] <^>const url = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR";<^> const { createApp } = Vue createApp({ data() { return { <^>results:[]<^> } <^>},<^> <^>mounted() {<^> <^>axios.get(url).then(response => {<^> <^>this.results = response.data<^> <^>})<^> } }).mount('#app') ``` Notice we've removed the default value for `results` and replaced it with an empty array. We won't have data when our app first loads, but the HTML view is expecting some data to iterate over when it loads. The `axios.get` function uses a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises). When the API returns data successfully, the code within the `then` block is executed, and the data gets saved to our `results` variable. Save the file and reload the `index.html` page in the web browser. This time, you'll see the current prices of the cryptocurrencies. If you don't see anything, you can review [How To Use the JavaScript Developer Console](https://www.digitalocean.com/community/tutorials/how-to-use-the-javascript-developer-console) and use the JavaScript console to debug your code. The page may take a minute to refresh with data from the API. You can also view this [Github repository](https://github.com/do-community/vue-axios), which contains the `html` and `js` files that you can download for cross-confirmation. You can also clone the [repository](https://github.com/do-community/vue-axios). In this step, you modified your app to call live data for review. ## Conclusion In less than fifty lines, you created an API-consuming application using only three tools: Vue.js, Axios, and the Cryptocompare API. You learned how to display data on a page, iterate over results, and replace static data with results from an API. Now that you understand the fundamentals, you can add other functionality to your application. Modify this application to display additional currencies, or use the techniques you learned in this tutorial to create another web applications using a different API.

Источник: DigitalOcean Community Tutorials

Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.