App下載

在vue.js中如何使用axios訪問api?如何使用axios訪問api經(jīng)驗分享!

猿友 2021-06-22 15:45:49 瀏覽數(shù) (2872)
反饋

相信很多人都有聽過api連接,那么今天我們就來說說有關(guān)于“在vue.js中如何使用axios訪問api?”這個問題吧!下面小編整理的相關(guān)資料希望對大家有所幫助!


1、在很多時候在我們要構(gòu)建應(yīng)用時都需要訪問一個 API 并展示其數(shù)據(jù)。但是對于做這件事的方法有好幾種,下面我們來說下最流行的一種吧!使用基于 ?promise? 的 HTTP 客戶端 axios 。然而在我們這次分享中,我們會使用 ?CoinDesk API? 來完成展示比特幣價格且每分鐘更新的工作。


2、首先,我們要通過 npm/Yarn 或一個 CDN 鏈接安裝 axios。

我們有很多種方式可以從 API 請求信息,但是最好首先確認(rèn)這些數(shù)據(jù)看起來長什么樣,以便進(jìn)一步確定如何展示它。從而我們會調(diào)用一次這個 API 并輸出結(jié)果,以便我們能夠看清楚它。就像 CoinDesk 的 API 文檔中所說的,請求會發(fā)送到 https://api.coindesk.com/v1/bpi/currentprice.json。所以,我們首先創(chuàng)建一個 ?data? 里的 ?property? 以最終放置信息,然后將會在 mounted 生命周期鉤子中獲取數(shù)據(jù)并賦值過去代碼如下:

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>

    

當(dāng)我們執(zhí)行完成之后會得到下面這樣:

{ "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": {} }

這樣子我們已經(jīng)得到的部分?jǐn)?shù)據(jù),但是看起來卻很亂,那么接下來我們需要為它添加一些處理,以防出現(xiàn)異常情況或請求超時。


3、api數(shù)據(jù)展示

在正擦的情況下,我們需要的信息已經(jīng)包含在了響應(yīng)中,所以只需要遍歷我們保存下來的內(nèi)容就能正確地獲取。在下面這個例子中,我們就可以看到我們需要的價格信息在 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 } }

通過上面的兩部分亂碼對比,我們發(fā)現(xiàn)第二次的亂碼會比第一次好了許多,這也讓展示的工作變得容易了很多,所以我們可以更新 HTML 以從獲取的數(shù)據(jù)中僅僅展示真正需要的信息。那么接下來我們會創(chuàng)建一個過濾器來確保小數(shù)部分的合理展示。代碼如下:

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

js代碼部分:

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

結(jié)果如下:

結(jié)果截圖


4、錯誤處理

在很多的時候我們并沒有從?API?中獲取到自己想要的數(shù)據(jù),這是有很多因素引起的,一下是有關(guān)于?axios?調(diào)用失敗的一些原因(但是不僅限于這些):

  • API不工作;
  • 請求發(fā)錯;
  • API沒有按照我們的預(yù)期格式返回信息。

還有當(dāng)我們在發(fā)送請求的時候,我們應(yīng)該檢查一下上面提到的這些情況,并且在所有情況下都返回相應(yīng)的信息從而方便處理這些問題,一般我們在?axios?中會使用?catch?來做事件,代碼如下:

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

我們通過這樣的設(shè)置我們就可以知道請求?API?的過程中是否有地方出錯了,那么如果數(shù)據(jù)長時間生成不出來或者?API?不工作會是怎么樣的呢?下面我們就來構(gòu)建在無法獲取數(shù)據(jù)時通知用戶的加載效果,代碼如下:

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

我們可以在例子中點(diǎn)擊 ?Rerun? 按鈕以便看到我們從 ?API? 獲取數(shù)據(jù)時的加載狀態(tài)。


5、替代方案

Fetch API 

對于Fetch API 它是一個用于此類請求的強(qiáng)大的原生 API。它的好處就是你不需要在使用它的時候額外加載一個外部資源。但是的話目前它還沒有被瀏覽器完全支持,所以我們?nèi)匀恍枰粋€ polyfill。


總結(jié):

以上就是有關(guān)于“在vue.js中如何使用axios訪問api?”這個問題的相關(guān)內(nèi)容,當(dāng)然如果你有其他的看法也可以提出來和大家一起分享!更多有關(guān)于vue.js的相關(guān)知識內(nèi)容我們都可以在W3CSCHOOL中進(jìn)行學(xué)習(xí)和了解。


相關(guān)資料鏈接:

CoinDesk API :https://www.coindesk.com/coindesk-api

vue過濾器:https://cn.vuejs.org/v2/api/#Vue-filter


0 人點(diǎn)贊