[Vue.js] 使用 Axios 在網頁讀取時處理載入後的 API 內容
我們在 vue 要處理類似以往的 ajax 讀取時,現在推薦的是使用 axios 來處理,這邊是設定在網頁載入時就讀取 api 的寫法。
把內容顯示出來會長這樣。
如果想要拿其中的內容:
結果:
可以再繼續對取回的內容做處理:
就會回傳 code=USD 的那一項的內容
參考:Using Axios to Consume APIs
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 }}
{ "data": { "time": { "updated": "Aug 11, 2019 02:04:00 UTC", "updatedISO": "2019-08-11T02:04:00+00:00", "updateduk": "Aug 11, 2019 at 03:04 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": "11,352.0083", "description": "United States Dollar", "rate_float": 11352.0083 }, "GBP": { "code": "GBP", "symbol": "£", "rate": "9,430.1133", "description": "British Pound Sterling", "rate_float": 9430.1133 }, "EUR": { "code": "EUR", "symbol": "€", "rate": "10,063.3965", "description": "Euro", "rate_float": 10063.3965 } } }, "status": 200, "statusText": "OK", "headers": { "cache-control": "max-age=15", "content-type": "application/javascript", "expires": "Sun, 11 Aug 2019 02:05: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": {} }
如果想要拿其中的內容:
axios .get('https://api.coindesk.com/v1/bpi/currentprice.json') .then(response => (this.info = response.data.bpi))
結果:
{ "USD": { "code": "USD", "symbol": "$", "rate": "11,352.0083", "description": "United States Dollar", "rate_float": 11352.0083 }, "GBP": { "code": "GBP", "symbol": "£", "rate": "9,430.1133", "description": "British Pound Sterling", "rate_float": 9430.1133 }, "EUR": { "code": "EUR", "symbol": "€", "rate": "10,063.3965", "description": "Euro", "rate_float": 10063.3965 } }
可以再繼續對取回的內容做處理:
axios .get('https://api.coindesk.com/v1/bpi/currentprice.json') .then(response => { this.info= response.data.bpi.filter( d=> d.code=="USD") } )
就會回傳 code=USD 的那一項的內容
參考:Using Axios to Consume APIs
留言