Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use axios to access api in vue.js

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "how to use axios to access api in vue.js", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to use axios to access api in vue.js" can help you solve your doubts.

1. In many cases, when we want to build an application, we need to access an API and display its data. But there are several ways to do it, so let's talk about the most popular one. Use the promise-based HTTP client axios. However, in our sharing, we will use CoinDesk API to show the price of bitcoin and update it every minute.

2. First, we will install axios through npm/Yarn or a CDN link.

There are many ways to request information from API, but it's best to first confirm what the data looks like in order to further determine how to present it. So we will call the API once and output the result so that we can see it clearly. As stated in CoinDesk's API document, the request is sent to https://api.coindesk.com/v1/bpi/currentprice.json. So, we first create a property in data to finally place the information, and then we will get the data in the mounted lifecycle hook and assign the past code as follows:

New Vue ({el:'# app', data () {return {info: null}}, mounted () {axios .get ('https://api.coindesk.com/v1/bpi/currentprice.json'). Then (response = > (this.info = response))}}) {{info}}

When we finish the execution, we will get something like this:

{"data": {"time": {"updated": "Jun 22, 2021 06:59:00 UTC", "updatedISO": "2021-06-22T06:59:00+00:00", "updateduk": "Jun 22, 2021 at 07:59 BST"}, "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org "," chartName ":" Bitcoin "," bpi ": {" USD ": {" code ":" USD "," symbol ":" $"," rate ":" 32793.0171 "," description ":" United States Dollar "," rate_float ": 32793.0171}," GBP ": {" code ":" GBP "," symbol ":" £" "rate": "23602.0854", "description": "British Pound Sterling", "rate_float": 23602.0854}, "EUR": {"code": "EUR", "symbol": "rate": "27576.1727", "description": "Euro", "rate_float": 27576.1727}, "status": 200, "statusText": "" "headers": {"cache-control": "max-age=15", "content-length": "679", "content-type": "application/javascript", "expires": "Tue, 22 Jun 2021 07:01:07 UTC"}, "config": {"transformRequest": {}, "transformResponse": {}, "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN" "maxContentLength":-1, "headers": {"Accept": "application/json, text/plain, * / *"}, "method": "get", "url": "https://api.coindesk.com/v1/bpi/currentprice.json"}," request ": {}}

This way we've got some of the data, but it looks messy, so we need to add some processing to it in case there is an exception or the request timed out.

3. Api data display

In the case of erasing, the information we need is already included in the response, so we only need to traverse what we have saved to get it correctly. In the following example, we can see that the price information we need is in response.data.bpi. If we switch to this, the output looks like this:

The js code section is as follows:

Axios. Get ('https://api.coindesk.com/v1/bpi/currentprice.json'). Then (response = > (this.info = response.data.bpi))

The garbled part is as follows:

{"USD": {"code": "USD", "symbol": "$", "rate": "32793.0171", "description": "United States Dollar", "rate_float": 32793.0171}, "GBP": {"code": "GBP", "symbol": "£", "rate": "23602.0854", "description": "British Pound Sterling", "rate_float": 23602.0854} "EUR": {"code": "EUR", "symbol": "rate": "27576.1727", "description": "Euro", "rate_float": 27576.1727}}

Through the comparison of the two parts of garbled code above, we find that the garbled code in the second time is much better than that in the first time, which makes the work of the presentation much easier, so we can update HTML to show only the information we really need from the data obtained. Then we will create a filter to ensure that the decimal parts are properly displayed. The code is as follows:

Bitcoin Price Index {{currency.description}}: {{currency.rate_float | currencydecimal}}

Js code section:

Filters: {currencydecimal (value) {return value.toFixed (2)}}

4. Error handling

In many cases, we do not get the data we want from API, which is caused by many factors. Here are some reasons for the failure of axios calls (but not limited to these):

API does not work

Request sent in error

API did not return the information in the format we expected.

Also, when we send a request, we should check the situations mentioned above and return the corresponding information in all cases to facilitate dealing with these problems. Generally, we use catch to do events in axios. The code is as follows:

Axios .get ('https://api.coindesk.com/v1/bpi/currentprice.json'). Then (response = > (this.info = response.data.bpi)) .catch (error = > console.log (error))

Through this setting, we can know if there is anything wrong with the request for API, so what if the data is not generated for a long time or the API does not work? Let's build the loading effect of notifying the user when the data cannot be obtained, as follows:

New Vue ({el:'# app', data () {return {info: null, loading: true, errored: false}}, filters: {currencydecimal (value) {return value.toFixed (2)}} Mounted () {axios .get ('https://api.coindesk.com/v1/bpi/currentprice.json') .then (response = > {this.info = response.data.bpi}) .catch (error = > {console.log (error) this.errored = true}) .finally (() = > this.loading = false)})

Part of the Html code:

Bitcoin Price Index

We're sorry, we're not able to retrieve this information at the moment, please try back later

Loading... {{currency.description}}: {{currency.rate_float | currencydecimal}}

We can click the Rerun button in the example to see the loading status when we get the data from API.

5. Alternative scheme

Fetch API

For Fetch API it is a powerful native API for such requests. The advantage of it is that you don't need to load an extra external resource when using it. However, it is not fully supported by browsers yet, so we still need a polyfill.

After reading this, the article "how to use axios to access api in vue.js" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report