Use axios to access API in vue

Unlike jQuery, Vue has a built-in ajax request function, and Vue does not provide such a function. So when we need to communicate with the server in Vue, the options available will be more flexible.
So Vue gives us more choices. For example, we can use the following options:

  • Native XMLHttpRequest
  • Native Fetch
  • You can also use the Ajax request function that comes with jQuery
  • In the early days, everyone liked to use a third-party plug-in when developing Vue applications: Vue Resource
  • The current mainstream solution is to use axios, a well-known third-party library in the community.

1. Basic example

Many times when building an application you need to access an API and display its data. There are several ways to do this, and using the promise-based HTTP client axios is a very popular one.

In this practice, we will use the CoinDesk API to display the price of Bitcoin and update it every minute. First, we need to install axios via npm/Yarn or a CDN link.

There are many ways to request information from the API, but it's best to first confirm what the data looks like so you can further determine how to display it. To do this, we will call this API once and print the result so that we can see it clearly. As stated in CoinDesk's API documentation, requests are sent to https://api.coindesk.com/v1/bpi/currentprice.json. So, we first create an attribute in data to finally place the information, and then we will get the data in the mounted life cycle hook and assign it:

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

What we get is this:
Check out Vue (@Vue)'s axios and Vue: Step 1 in CodePen.

very good! We've got some data. But it still looks messy, so we'll show it off better and add some error handling in case something unexpected happens or the request times out.

2. Real-world examples: working with data

Display data from an API

Usually, the information we need is already included in the response, and we only need to iterate through the content we saved to obtain it correctly. In this example, we can see that the price information we need is in response.data.bpi. If we use this instead, the output looks like this:

axios
  .get('https://api.coindesk.com/v1/bpi/currentprice.json')
  .then(response => (this.info = response.data.bpi))

Check out axios for Vue (@Vue) and Vue: Step 2 on CodePen.

This makes the presentation job a lot easier, so we can update the HTML to present only the information we really need from the fetched data. We will create a filter to ensure that the decimal part is properly displayed.

<div id="app">
  <h1>Bitcoin Price Index</h1>
  <div
    v-for="currency in info"
    class="currency"
  >
    {
   
   { currency.description }}:
    <span class="lighten">
      <span v-html="currency.symbol"></span>{
   
   { currency.rate_float | currencydecimal }}
    </span>
  </div>
</div>
filters: {
    
    
  currencydecimal (value) {
    
    
    return value.toFixed(2)
  }
},

Check out Vue (@Vue)’s axios and Vue: Step 3 on CodePen.

Error handling

Many times we may not get the data we want from the API. This could be due to a number of factors, for example the axios call could fail for a number of reasons, including but not limited to

  • API doesn't work anymore
  • wrong request
  • The API does not return information in the format we expect. When sending this request, we should check for these conditions and return appropriate information in all cases to handle these problems. In axios, we do this by using catch.
axios
  .get('https://api.coindesk.com/v1/bpi/currentprice.json')
  .then(response => (this.info = response.data.bpi))
  .catch(error => console.log(error))

This way we will know if something went wrong during the request to the API, but what happens when the data cannot be generated for a long time or the API does not work? Now the user will see nothing. We might want to build a loading effect for this situation and then notify the user when the data cannot be fetched at all.

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)
  }
})
<div id="app">
  <h1>Bitcoin Price Index</h1>
  <section v-if="errored">
    <p>We're sorry, we're not able to retrieve this information at the moment, please try back later</p>
  </section>
  <section v-else>
    <div v-if="loading">Loading...</div>
    <div
      v-else
      v-for="currency in info"
      class="currency"
    >
      {
   
   { currency.description }}:
      <span class="lighten">
        <span v-html="currency.symbol"></span>{
   
   { currency.rate_float | currencydecimal }}
      </span>
    </div>
  </section>
</div>

You can click the Rerun button in the example below to see the loading status when we get data from the API:

Check out Vue (@Vue)’s axios and Vue: Step 4 on CodePen.

We can also make further optimizations, such as using components to implement different parts and giving clearer error reports. It all depends on the API you use and the complexity of your application.

3. Alternatives

Fetch API
Fetch API is a powerful native API for such requests. You may have heard that one of the benefits of the Fetch API is that you don't need to load an additional external resource when using it. Indeed! But... currently it's not fully supported by browsers, so you'll still need a polyfill. There are many other things to note when using this API, which is why everyone still prefers axios at this stage. Of course this may change in the future.

4. Summary

In fact, Vue and axios can work together for more than just accessing and displaying an API. You can also communicate with Serverless Functions, sending publish/edit/delete requests, etc. to an API with write permissions. Because the integration of these two libraries is simple and straightforward, it has become a common choice for developers who need to integrate HTTP clients into their workflows.

Guess you like

Origin blog.csdn.net/javascript_good/article/details/132430689