如何在 Vue 中使用 Axios 異步請(qǐng)求API
設(shè)置基本 HTTP 請(qǐng)求
首先在終端中執(zhí)行下面的命令把 Axios 安裝到項(xiàng)目中:
install?axiosnpm?install?axios
然后,在 Vue 組件中像這樣導(dǎo)入axios。
//App.vie?-?importing?axios <script> import?axios?from?'axios' export?default?{ ??setup?()?{ ?? ??} } </script>
接下來(lái)用 axios.get 通過(guò) Kanye REST API 的 URL 獲取隨機(jī)語(yǔ)錄。之后可以用 Promise.then 等待請(qǐng)求返回響應(yīng)。
//App.vue?-?sending?our?HTTP?request <script> import?axios?from?'axios' export?default?{ ??setup?()?{ ?????axios.get('https://api.kanye.rest/').then(response?=>?{ ????????//?handle?response ?????}) ??} } </script>
現(xiàn)在可以從 API 中獲取響應(yīng)了,先看一下它的含義。把它保存成名為 quote 的引用。
//App.vue?-?storing?the?response <script> import?axios?from?'axios' import?{?ref?}?from?'vue' export?default?{ ??setup?()?{ ?????axios.get('https://api.kanye.rest/').then(response?=>?{ ????????//?handle?response ????????quote.value?=?response ?????}) ?????return?{ ??????quote ?????} ??} } </script>
最后將其輸出到模板中并以斜體顯示,并用引號(hào)引起來(lái),另外還需要給這條語(yǔ)錄加上引用來(lái)源。
//App.vue?-?template?code <template> ??<div> ????<i>"{{?quote?}}"</i> ????<p>-?Kanye?West</p> ??</div> </template>
檢查一下瀏覽器中的內(nèi)容。
我們可以看到隨機(jī)返回的侃爺語(yǔ)錄,還有一些額外的信息,例如請(qǐng)求的響應(yīng)碼等。
對(duì)于我們這個(gè)小應(yīng)用,只對(duì)這個(gè) data.quote 值感興趣,所以要在腳本中指定要訪問(wèn) response 上的哪個(gè)屬性。
//App.vue?-?getting?only?our?quote axios.get('https://api.kanye.rest/').then(response?=>?{ ????????//?handle?response ????????quote.value?=?response.data.quote })
通過(guò)上面的代碼可以得到想要的內(nèi)容:
Axios 配合 async/await
可以在 Vue 程序中把 Axios 和 async /await 模式結(jié)合起來(lái)使用。
在設(shè)置過(guò)程中,首先注釋掉當(dāng)前的 GET 代碼,然后創(chuàng)建一個(gè)名為 loadQuote 的異步方法。在內(nèi)部,可以使用相同的 axios.get 方法,但是我們想用 async 等待它完成,然后把結(jié)果保存在一個(gè)名為 response 的常量中。
然后設(shè)置 quote 的值。
//App.vue?-?async?Axios const?loadQuote?=?async?()?=>?{ ??????const?response?=?await?KanyeAPI.getQuote() ??????quote.value?=?response.data.quote }
它和前面的代碼工作原理完全一樣,但這次用了異步模式。
Axios 的錯(cuò)誤處理
在 async-await 模式中,可以通過(guò) try 和 catch 來(lái)為 API 調(diào)用添加錯(cuò)誤處理:
//Error?handling?with?async/await try?{ ????????const?response?=?await?KanyeAPI.getQuote() ????????quote.value?=?response.data.quote }?catch?(err)?{ ????????console.log(err) }
如果使用原始的 promises 語(yǔ)法,可以在 API 調(diào)用之后添加 .catch 捕獲來(lái)自請(qǐng)求的任何錯(cuò)誤。
//Error?handling?with?Promises axios.get('https://api.kanye.rest/') ??????.then(response?=>?{ ????????//?handle?response ????????quote.value?=?response.data.quote ??????}).catch(err?=>?{ ??????console.log(err) })
發(fā)送POST請(qǐng)求
下面看一下怎樣發(fā)送 POST 請(qǐng)求。在這里我們使用 JSONPlaceholder Mock API 調(diào)用。
他們的文檔中提供了一個(gè)測(cè)試 POST 請(qǐng)求的 /posts 接口。
接下來(lái)我們需要?jiǎng)?chuàng)建一個(gè)按鈕,當(dāng)點(diǎn)擊按鈕時(shí)將會(huì)觸發(fā)我們的API調(diào)用。在模板中創(chuàng)建一個(gè)名為 “Create Post” 的按鈕,單擊時(shí)調(diào)用名為 createPost 方法。
??<div> ????<i>"{{?quote?}}"</i> ????<p>-?Kanye?West</p> ????<p> ??????<button?@click="createPost">Create?Post</button> ????</p> ??</div> </template>
下面在代碼中創(chuàng)建 createPost 方法,然后從 setup 返回。
這個(gè)方法,類似于前面的 GET 請(qǐng)求,只需要調(diào)用 axios.post 并傳入U(xiǎn)RL(即https://jsonplaceholder.typicode.com/posts )就可以復(fù)制粘貼文檔中的數(shù)據(jù)了。
//App.vue const?createPost?=?()?=>?{ ??????axios.post('https://jsonplaceholder.typicode.com/posts',?JSON.stringify({ ??????????title:?'foo', ??????????body:?'bar', ??????????userId:?1, ??????})).then(response?=>?{ ????????console.log(response) ??????}) }
單擊按鈕試一下,可以看到控制臺(tái)輸出了大量信息,告訴我們 POST 請(qǐng)求已成功完成。
用 Axios 編寫可復(fù)用的 API 調(diào)用
在項(xiàng)目中通過(guò)創(chuàng)建一個(gè) src/services 目錄,用它來(lái)組織所有 api 調(diào)用。
目錄中包含 2 種類型的文件:
- API.js :用來(lái)創(chuàng)建一個(gè)帶有定義的 baseURL 的 Axios 實(shí)例,這個(gè)實(shí)例會(huì)用于所有的路由
- *{specific functionality}*API.js :更具體的文件,可用于將 api 調(diào)用組織成可重用的模塊
這樣做的好處是可以方便的在開(kāi)發(fā)和生產(chǎn)服務(wù)器之間進(jìn)行切換,只需修改一小段代碼就行了。
創(chuàng)建 services/API.js 文件,并將 Axios baseURL 設(shè)置為默認(rèn)為 Kanye REST API。
API.jsimport?axios?from?'axios' export?default(url='https://api.kanye.rest')?=>?{ ????return?axios.create({ ????????baseURL:?url, ????}) }
接下來(lái)創(chuàng)建一個(gè) KanyeAPI.js 文件并從 ./API 中導(dǎo)入 API。在這里我們要導(dǎo)出不同的 API 調(diào)用。
調(diào)用 API() 會(huì)給得到一個(gè) Axios 實(shí)例,可以在其中調(diào)用 .get 或 .post。
//KanyeAPI.js import?API?from?'./API' export?default?{ ????getQuote()?{ ????????return?API().get('/') ????}, }
然后在 App.vue 內(nèi)部,讓我們的組件通過(guò)可復(fù)用的 API 調(diào)用來(lái)使用這個(gè)新文件,而不是自己再去創(chuàng)建 Axios。
//App.vue const?loadQuote?=?async?()?=>?{ ??????try?{ ????????const?response?=?await?KanyeAPI.getQuote()?//?<---?THIS?LINE ????????quote.value?=?response.data.quote ??????}?catch?(err)?{ ????????console.log(err) ??????} }
下面把 createPost 移到其自己的可重用方法中。
回到 KanyeAPI.js 在導(dǎo)出默認(rèn)設(shè)置中添加 createPost,這會(huì)將 POST 請(qǐng)求的數(shù)據(jù)作為參數(shù)傳遞給我們的 HTTP 請(qǐng)求。
與GET請(qǐng)求類似,通過(guò) API 獲取 axios 實(shí)例,但這次需要覆蓋默認(rèn) URL 值并傳遞 JSONplaceholder url。然后就可以像過(guò)去一樣用 Axios POST 了。
//KanyeAPI.js export?default?{ ????getQuote()?{ ????????return?API().get('/') ????}, ????createPost(data)?{ ????????return?API('https://jsonplaceholder.typicode.com/').post('/posts',?data) ????} }
如此簡(jiǎn)單
回到 App.vue ,可以像這樣調(diào)用新的 post 方法。
//App.vue? const?createPost?=?()?=>?{ ??????const?response?=?await?KanyeAPI.createPost(JSON.stringify({ ??????????title:?'foo', ??????????body:?'bar', ??????????userId:?1, ??????})) ??????console.log(response) }
現(xiàn)在單擊按鈕時(shí),可以看到專用的 API 能夠正常工作。
把 API 調(diào)用移出這些 Vue 組件并放在它自己的文件的好處在于,可以在整個(gè)程序中的任何位置使用這些 API 調(diào)用。這樣可以創(chuàng)建更多可重用和可伸縮的代碼。
最終代碼
//?App.vue <template> ??<div> ????<i>"{{?quote?}}"</i> ????<p>-?Kanye?West</p> ????<p> ??????<button?@click="createPost">Create?Post</button> ????</p> ??</div> </template> <script> import?axios?from?'axios' import?{?ref?}?from?'vue' import?KanyeAPI?from?'./services/KanyeAPI' export?default?{ ??setup?()?{ ????const?quote?=?ref('') ????const?loadQuote?=?async?()?=>?{ ??????try?{ ????????const?response?=?await?KanyeAPI.getQuote() ????????quote.value?=?response.data.quote ??????}?catch?(err)?{ ????????console.log(err) ??????} ????} ????loadQuote() ???? ????//?axios.get('https://api.kanye.rest/') ????//???.then(response?=>?{ ????//?????//?handle?response ????//?????quote.value?=?response.data.quote ????//???}).catch(err?=>?{ ????//???console.log(err) ????//?}) ????const?createPost?=?()?=>?{ ??????const?response?=?await?KanyeAPI.createPost(JSON.stringify({ ??????????title:?'foo', ??????????body:?'bar', ??????????userId:?1, ??????})) ??????console.log(response) ??????//?axios.post('https://jsonplaceholder.typicode.com/posts',?JSON.stringify({ ??????//?????title:?'foo', ??????//?????body:?'bar', ??????//?????userId:?1, ??????//?})).then(response?=>?{ ??????//???console.log(response) ??????//?}) ?????? ????} ???? ????return?{ ??????createPost, ??????quote ????} ??} } </script> <style> #app?{ ??font-family:?Avenir,?Helvetica,?Arial,?sans-serif; ??-webkit-font-smoothing:?antialiased; ??-moz-osx-font-smoothing:?grayscale; ??text-align:?center; ??color:?#2c3e50; ??margin-top:?60px; } </style>
//API.js import?axios?from?'axios' export?default(url='https://api.kanye.rest')?=>?{ ????return?axios.create({ ????????baseURL:?url, ????}) }
//KanyeAPI.js import?API?from?'./API' export?default?{ ????getQuote()?{ ????????return?API().get('/') ????}, ????createPost(data)?{ ????????return?API('https://jsonplaceholder.typicode.com/').post('/posts',?data) ????} }
以上就是如何在 Vue 中用 Axios 異步請(qǐng)求API的詳細(xì)內(nèi)容,更多關(guān)于Vue 用 Axios 異步請(qǐng)求API的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
一個(gè)Vue視頻媒體多段裁剪組件的實(shí)現(xiàn)示例
這篇文章主要介紹了一個(gè)Vue媒體多段裁剪組件的實(shí)現(xiàn)示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08vue組件Prop傳遞數(shù)據(jù)的實(shí)現(xiàn)示例
本篇文章主要介紹了vue組件Prop傳遞數(shù)據(jù)的實(shí)現(xiàn)示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08Vue之修改數(shù)據(jù)頁(yè)面不更新的問(wèn)題
這篇文章主要介紹了Vue之修改數(shù)據(jù)頁(yè)面不更新的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12vue2.0 兄弟組件(平級(jí))通訊的實(shí)現(xiàn)代碼
這篇文章主要介紹了vue2.0 兄弟組件(平級(jí))通訊的實(shí)現(xiàn)代碼,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-01-01Vue3后臺(tái)管理系統(tǒng)之創(chuàng)建和配置項(xiàng)目
后臺(tái)管理系統(tǒng)是我們?nèi)粘i_(kāi)發(fā)學(xué)習(xí)經(jīng)常遇到的一個(gè)項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于Vue3后臺(tái)管理系統(tǒng)之創(chuàng)建和配置項(xiàng)目的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09vue2 中使用 render 函數(shù)編寫組件的方式
vue提供了聲明式編寫UI的方式,即vue提供了對(duì)DOM進(jìn)行描述的方式,有兩種描述DOM的方式即模板和render 函數(shù),本文通過(guò)示例代碼介紹vue2 中使用 render 函數(shù)編寫組件的方式,感興趣的朋友跟隨小編一起看看吧2024-06-06