vue.js中怎么使用axios访问api

发布时间:2022-01-26 16:36:46 作者:iii
来源:亿速云 阅读:140

本文小编为大家详细介绍“vue.js中怎么使用axios访问api”,内容详细,步骤清晰,细节处理妥当,希望这篇“vue.js中怎么使用axios访问api”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1、在很多时候在我们要构建应用时都需要访问一个 API 并展示其数据。但是对于做这件事的方法有好几种,下面我们来说下最流行的一种吧!使用基于 promise 的 HTTP 客户端 axios 。然而在我们这次分享中,我们会使用 CoinDesk API 来完成展示比特币价格且每分钟更新的工作。


2、首先,我们要通过 npm/Yarn 或一个 CDN 链接安装 axios。

我们有很多种方式可以从 API 请求信息,但是最好首先确认这些数据看起来长什么样,以便进一步确定如何展示它。从而我们会调用一次这个 API 并输出结果,以便我们能够看清楚它。就像 CoinDesk 的 API 文档中所说的,请求会发送到 https://api.coindesk.com/v1/bpi/currentprice.json。所以,我们首先创建一个 data 里的 property 以最终放置信息,然后将会在 mounted 生命周期钩子中获取数据并赋值过去代码如下:

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>

当我们执行完成之后会得到下面这样:

{ "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": "&#36;", "rate": "32,793.0171", "description": "United States Dollar", "rate_float": 32793.0171 }, "GBP": { "code": "GBP", "symbol": "&pound;", "rate": "23,602.0854", "description": "British Pound Sterling", "rate_float": 23602.0854 }, "EUR": { "code": "EUR", "symbol": "&euro;", "rate": "27,576.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": {} }

这样子我们已经得到的部分数据,但是看起来却很乱,那么接下来我们需要为它添加一些处理,以防出现异常情况或请求超时。


3、api数据展示

在正擦的情况下,我们需要的信息已经包含在了响应中,所以只需要遍历我们保存下来的内容就能正确地获取。在下面这个例子中,我们就可以看到我们需要的价格信息在 response.data.bpi 中。如果我们换用这个,则输出是下面这样的:

js代码部分如下:

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

乱码部分如下:

{ "USD": { "code": "USD", "symbol": "&#36;", "rate": "32,793.0171", "description": "United States Dollar", "rate_float": 32793.0171 }, "GBP": { "code": "GBP", "symbol": "&pound;", "rate": "23,602.0854", "description": "British Pound Sterling", "rate_float": 23602.0854 }, "EUR": { "code": "EUR", "symbol": "&euro;", "rate": "27,576.1727", "description": "Euro", "rate_float": 27576.1727 } }

通过上面的两部分乱码对比,我们发现第二次的乱码会比第一次好了许多,这也让展示的工作变得容易了很多,所以我们可以更新 HTML 以从获取的数据中仅仅展示真正需要的信息。那么接下来我们会创建一个过滤器来确保小数部分的合理展示。代码如下:

<div id="app">
  <h2>Bitcoin Price Index</h2>
  <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>

js代码部分:

filters: {
  currencydecimal (value) {
    return value.toFixed(2)
  }
},

4、错误处理

在很多的时候我们并没有从API中获取到自己想要的数据,这是有很多因素引起的,一下是有关于axios调用失败的一些原因(但是不仅限于这些):

还有当我们在发送请求的时候,我们应该检查一下上面提到的这些情况,并且在所有情况下都返回相应的信息从而方便处理这些问题,一般我们在axios中会使用catch来做事件,代码如下:

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

我们通过这样的设置我们就可以知道请求API的过程中是否有地方出错了,那么如果数据长时间生成不出来或者API不工作会是怎么样的呢?下面我们就来构建在无法获取数据时通知用户的加载效果,代码如下:

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)
  }
})

Html部分代码:

<div id="app">
  <h2>Bitcoin Price Index</h2>

  <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>

我们可以在例子中点击 Rerun 按钮以便看到我们从 API 获取数据时的加载状态。


5、替代方案

Fetch API 

对于Fetch API 它是一个用于此类请求的强大的原生 API。它的好处就是你不需要在使用它的时候额外加载一个外部资源。但是的话目前它还没有被浏览器完全支持,所以我们仍然需要一个 polyfill。

读到这里,这篇“vue.js中怎么使用axios访问api”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. Vue.js 中 axios 跨域访问错误问题及解决方法
  2. vue.js如何配置axios

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue.js axios api

上一篇:Python Pyecharts怎么绘制象形柱图

下一篇:@Transactional注解怎么用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》