fetch網(wǎng)絡請求封裝示例詳解
更新時間:2021年11月23日 16:04:12 作者:tby_37
這篇文章主要介紹了fetch網(wǎng)絡請求封裝的示例內容詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

export default ({
url,
method = 'GET',
data = null,
}) => {
// 請求配置
let options = {
method
}
// data不為空時,它就是post請求
if (data) {
options = {
...options,
body: JSON.stringify(data),
headers: {
'content-type': 'application/json'
}
}
}
return fetch(url, options)
.then(res => res.json())
.then(data => data)
}
使用
get

post?
<script type="module">
import fetchApi from './js/fetch.js'
const vm = new Vue({
el: '#app',
data: {
users: []
},
// 發(fā)起網(wǎng)絡請求
mounted() {
let url = 'http://localhost:3000/api/users'
// fetchApi({ url }).then(data => console.log(data))
fetchApi({ url, method: 'POST', data: { id: 200, name: 'aaa' } }).then(data => console.log(data))
}
})
</script>
以上就是fetch網(wǎng)絡請求封裝示例詳解的詳細內容,更多關于fetch網(wǎng)絡請求封裝的資料請關注腳本之家其它相關文章!
相關文章
vue實現(xiàn)點擊按鈕“查看詳情”彈窗展示詳情列表操作
這篇文章主要介紹了vue實現(xiàn)點擊按鈕“查看詳情”彈窗展示詳情列表操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
vue中動態(tài)修改animation效果無效問題詳情
這篇文章主要介紹了vue中動態(tài)修改animation效果無效問題詳情,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-06-06
解決axios:"timeout of 5000ms exceeded"
這篇文章主要介紹了解決axios:"timeout of 5000ms exceeded"超時的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
Vue.directive 實現(xiàn)元素scroll邏輯復用
這篇文章主要介紹了Vue.directive 實現(xiàn)元素scroll邏輯復用功能,文中給大家提到元素實現(xiàn)滾動的條件有兩個,具體內容詳情大家參考下本文2019-11-11

