生活随笔
收集整理的這篇文章主要介紹了
vue项目请求封装;axios封装使用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
vue項(xiàng)目,封裝axios請(qǐng)求方式和響應(yīng)狀態(tài)碼;以及接口的api封裝;
目錄結(jié)構(gòu):
1.具體在src/utils/request.js下封裝axios:
①引入axios和router
②引入element-ui是為了用提示組件 和加載組件(可選擇去掉)
③根據(jù)請(qǐng)求攔截器的config配置請(qǐng)求頭
④根據(jù)響應(yīng)攔截器的不同狀態(tài)碼做不同處理(狀態(tài)碼需要自己根據(jù)項(xiàng)目修改)
簡(jiǎn)單的request.js封裝點(diǎn)擊這里,沒(méi)有封裝狀態(tài)碼和提示–可自己配
import axios
from "axios";
import router
from "./../router";
import { Message
, Loading
, MessageBox
} from "element-ui";
axios
.defaults
.baseURL
= "http://192.168.1.194/gateway";
axios
.defaults
.timeout
= 10000;let loading
;
axios
.interceptors
.request
.use(config
=> {let showLoading
= true;if (config
.loading
=== false) {showLoading
= false;}if (showLoading
) {loading
= Loading
.service({text
: "加載中...",spinner
: "el-icon-loading",background
: "rgba(0, 0, 0, 0.08)"});}config
.headers
["X-Requested-With"] = "XMLHttpRequest";config
.headers
["Token"] = "97aa8f6b569648c78005240033aa0438";return config
;},error
=> {return Promise
.reject(error
);}
);
axios
.interceptors
.response
.use(response
=> {console
.log("接口success", response
);loading
&& loading
.close();const { code
, data
, message
} = response
.data
;if (code
) {switch (code
) {case 200:return { code
, data
};case 3012:return { code
, data
};case 404:Message({message
: "網(wǎng)絡(luò)請(qǐng)求不存在",type
: "error",duration
: 2 * 1000});return Promise
.reject({ code
, data
});case 100:localStorage
.removeItem("token");router
.push({path
: "/login",querry
: {} });return Promise
.reject({ code
, data
});case 4011:Message
.closeAll();MessageBox
.alert("登錄超時(shí)或身份失效,請(qǐng)重新登錄!", "警告", {customClass
: "alertbox",confirmButtonText
: "確定",type
: "warning",center
: true,callback
: action
=> {router
.push("/");}});return Promise
.reject({ code
, data
});case 4002:default:Message({message
: message
|| "Error",type
: "error",duration
: 5 * 1000});return Promise
.reject({ code
, data
});}}},error
=> {loading
&& loading
.close();console
.log("接口error", error
, error
.response
);const { status
} = error
.response
;switch (status
) {case 500:Message
.closeAll();Message({message
: "請(qǐng)求超時(shí)",type
: "error",duration
: 3 * 1000});break;case 700:Message
.closeAll();Message({message
: "網(wǎng)絡(luò)中斷",type
: "error",duration
: 3 * 1000});break;default:Message({message
: error
.message
,type
: "error",duration
: 3 * 1000});}return Promise
.reject(error
);}
);const $http
= {};$http
.get = function(url
, data
, config
) {config
= config
|| {};config
.url
= url
;config
.method
= "get";config
.params
= data
;return axios
.request(config
);
};$http
.delete = function(url
, data
, config
) {config
= config
|| {};config
.url
= url
;config
.method
= "delete";config
.params
= data
;return axios
.request(config
);
};$http
.post = function(url
, data
, config
) {config
= config
|| {};config
.url
= url
;config
.method
= "post";config
.data
= data
;return axios
.request(config
);
};$http
.put = function(url
, data
, config
) {config
= config
|| {};config
.url
= url
;config
.method
= "put";config
.data
= data
;return axios
.request(config
);
};export { axios
, $http
};
2.接口方法封裝 src/api/way.js:
①引入封裝的$http
②使用$http.get(url,data,config) ; 下方的函數(shù)方法都是可以接受三個(gè)參數(shù)的 分別是 地址 參數(shù) 配置 三個(gè)參數(shù)可以由組件內(nèi)使用的函數(shù)function傳入
③在組件內(nèi)使用,接受傳遞的參數(shù)和配置(詳見(jiàn)test.vue組件內(nèi)的方法)
以下get post put delete 請(qǐng)求均有;且對(duì)于不同的請(qǐng)求需要配置的config也有
import { $http
} from '@/utils/request'
export function getlist() {return $http
.get(`main/queTactic/list`)
}
export function getClass(teacherId
) {return $http
.get(`/basis/teacher/queryTeacherClass/${teacherId}`)
}
export function getUrl() {return $http
.post(`/auth/api/authorize`)
}
export function getKnowledgeIdByChapterIds(data
) {return $http
.post(`/question/message/getKnowledgeIdByChapterIds`, data
)
}
export function editTactics(data
) {return $http
.put('main/queTactic', data
)
}
export function indiviDelete(data
) {return $http
.delete(`/main/personal/deleteQuestionPersonalJob`, data
)
}
export function downloadExcel(examId
) {return $http
.get(`main/statistics/report/${examId}/export/questionExcel`, null, { responseType
: 'blob' })
}
3.scr/views/test.vue在組件內(nèi)使用接口方法:
①引入way.js內(nèi)的接口方法:
②傳遞參數(shù)
③通過(guò).then()獲取使用
<template
><div
>接口返回參數(shù)
<div
>{{ data
}}</div
><!-- <el
-input v
-model
="input" placeholder
="請(qǐng)輸入內(nèi)容" /> --><button @click
="getlistRequest">get 獲取列表
</button
><button @click
="getClassRequest">get動(dòng)態(tài)參數(shù) 獲取班級(jí)
</button
><button @click
="btnRequest">post點(diǎn)擊獲取url
</button
><button @click
="getKnowledgeRequest">post傳參獲取知識(shí)點(diǎn)
</button
><button @click
="downloadExcelRequest">get文件流下載 配置config
</button
></div
>
</template
><script
>
import { getlist
, getUrl
, getClass
, getKnowledgeIdByChapterIds
, downloadExcel
} from '@/api/way.js'
export default {data() {return {input
: '',data
: null}},methods
: {getlistRequest() {getlist().then(res
=> {console
.log(res
.data
)this.data
= res
.data
})},getClassRequest() {const data
= 1932115674972160getClass(data
).then(res
=> {console
.log(res
.data
)this.data
= res
.data
})},btnRequest() {getUrl().then(res
=> { this.data
= res
.data
})},getKnowledgeRequest() {const data
= {chapterIds
: [22394],schoolId
: 39}getKnowledgeIdByChapterIds(data
).then(res
=> {console
.log(res
.data
)this.data
= res
.data
})},downloadExcelRequest() {const data
= 1943647285534911downloadExcel(data
).then(res
=> {const type
= 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'const blob
= new Blob([res
])const url
= window
.URL.createObjectURL(blob
, { type
: type
})const a
= document
.createElement('a')a
.href
= urldocument
.body
.appendChild(a
)a
.download
= '學(xué)情報(bào)告.xlsx'a
.click()window
.URL.revokeObjectURL(blob
)a
.remove()})}}
}
</script
><style
>
</style
>
4.頁(yè)面和接口展示:
成功200:
需要配置config的下載:
請(qǐng)求失敗提示:
總結(jié)
以上是生活随笔為你收集整理的vue项目请求封装;axios封装使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。