vue封裝axios的幾種方法
基礎(chǔ)版
第一步:配置axios
首先,創(chuàng)建一個(gè)Service.js,這里面存放的時(shí)axios的配置以及攔截器等,最后導(dǎo)出一個(gè)axios對(duì)象。我平常elementUI用的比較多,這里你也可以使用自己的UI庫(kù)。
import axios from 'axios'
import { Message, Loading } from 'element-ui'
const ConfigBaseURL = 'https://localhost:3000/' //默認(rèn)路徑,這里也可以使用env來(lái)判斷環(huán)境
let loadingInstance = null //這里是loading
//使用create方法創(chuàng)建axios實(shí)例
export const Service = axios.create({
timeout: 7000, // 請(qǐng)求超時(shí)時(shí)間
baseURL: ConfigBaseURL,
method: 'post',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
// 添加請(qǐng)求攔截器
Service.interceptors.request.use(config => {
loadingInstance = Loading.service({
lock: true,
text: 'loading...'
})
return config
})
// 添加響應(yīng)攔截器
Service.interceptors.response.use(response => {
loadingInstance.close()
// console.log(response)
return response.data
}, error => {
console.log('TCL: error', error)
const msg = error.Message !== undefined ? error.Message : ''
Message({
message: '網(wǎng)絡(luò)錯(cuò)誤' + msg,
type: 'error',
duration: 3 * 1000
})
loadingInstance.close()
return Promise.reject(error)
})
具體的攔截器邏輯以具體業(yè)務(wù)為準(zhǔn),我這里沒(méi)什么邏輯,只是加了一個(gè)全局的loading而已
第二步:封裝請(qǐng)求
這里我再創(chuàng)建一個(gè)request.js,這里面放的是具體請(qǐng)求。
import {Service} from './Service'
export function getConfigsByProductId(productId) {
return Service({
url: '/manager/getConfigsByProductId',
params: { productId: productId }
})
}
export function getAllAndroidPlugins() {
return Service({
url: '/manager/getAndroidPlugin ',
method: 'get'
})
}
export function addNewAndroidPlugin(data) {
return Service({
url: '/manager/addAndroidPlguin',
data: JSON.stringify(data)
})
}
當(dāng)然你也可以u(píng)rl再封裝一遍,放到另一個(gè)文件里,我覺(jué)得這樣并無(wú)什么意義,反而增加復(fù)雜度。這里主要注意的是起名問(wèn)題,建議按功能起名,例如我這里請(qǐng)求方式+功能或者內(nèi)容+參數(shù),這樣子直接看getConfigsByProductId這個(gè)名字也是很清晰明了
第三步:使用
在vue組件中
import {getAllAndroidPlugins,getConfigsByProductId,addNewAndroidPlugin} from '@/api/request.js'
getAllAndroidPlugins()
.then(res=>{
})
全局使用 在main.js中
import {Service} from '@/api/Service.js'
Vue.prototype.$axios=Service
進(jìn)階版
隨著vue cli的升級(jí),core-js\babel等依賴也隨之升級(jí),現(xiàn)在已經(jīng)可以隨心所欲的async/await了,因此本次封裝就是把之前的Promise升級(jí)成為async await. 首先,還是一樣,先封裝axios
//Service.js
import axios from 'axios'
const ConfigBaseURL = 'https://localhost:3000/' //默認(rèn)路徑,這里也可以使用env來(lái)判斷環(huán)境
//使用create方法創(chuàng)建axios實(shí)例
export const Service = axios.create({
timeout: 7000, // 請(qǐng)求超時(shí)時(shí)間
baseURL: ConfigBaseURL,
method: 'post',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
// 添加請(qǐng)求攔截器
Service.interceptors.request.use(config => {
return config
})
// 添加響應(yīng)攔截器
Service.interceptors.response.use(response => {
// console.log(response)
return response.data
}, error => {
return Promise.reject(error)
})
這時(shí)候你就獲取了一個(gè)axios對(duì)象,然后我推薦一個(gè)常用的庫(kù),主要用于處理async時(shí)的錯(cuò)誤:await-to-js。 代碼接上面的。
import to from 'await-to-js'
export function isObj(obj) {
const typeCheck = typeof obj!=='undefined' && typeof obj === 'object' && obj !== null
return typeCheck && Object.keys(obj).length > 0
}
export async function _get(url, qs,headers) {
const params = {
url,
method: 'get',
params: qs ? qs : ''
}
if(headers){params.headers = headers}
const [err, res] = await to(Service(params))
if (!err && res) {
return res
} else {
return console.log(err)
}
}
封裝get時(shí)只需要考慮parameter,使用await-to-js去捕獲await時(shí)的錯(cuò)誤,只在成功時(shí)返回?cái)?shù)據(jù),錯(cuò)誤時(shí)就會(huì)走攔截器。
export async function _get(url, qs,headers) {
const params = {
url,
method: 'get',
params: isObj(qs) ? qs : {}
}
if(isObj(headers)){params.headers = headers}
const [err, res] = await to(Service(params))
if (!err && res) {
return res
} else {
return console.log(err)
}
}
這是我封裝的post
export async function _post(url, qs, body) {
const params = {
url,
method: 'post',
params: isObj(qs) ? qs : {},
data: isObj(body) ? body : {}
}
const [err, res] = await to(Service(params))
if (!err && res) {
return res
} else {
return console.log(err)
}
}
使用的時(shí)候可以直接引入,也可以多次封裝
//a.vue
<srcipt>
improt{_get}from './Service'
export default{
methods:{
async test(){
const res = await _get('http://baidu.com')
}
}
}
</script>
以上就是vue封裝axios的幾種方法的詳細(xì)內(nèi)容,更多關(guān)于vue封裝axios的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
如何在 ant 的table中實(shí)現(xiàn)圖片的渲染操作
這篇文章主要介紹了如何在 ant 的table中實(shí)現(xiàn)圖片的渲染操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
vue-admin-template框架搭建及應(yīng)用小結(jié)
?vue-admin-template是基于vue-element-admin的一套后臺(tái)管理系統(tǒng)基礎(chǔ)模板(最少精簡(jiǎn)版),可作為模板進(jìn)行二次開發(fā),這篇文章主要介紹了vue-admin-template框架搭建及應(yīng)用,需要的朋友可以參考下2023-05-05
vue中數(shù)組常用的6種循環(huán)方法代碼示例
在vue項(xiàng)目開發(fā)中,我們需要對(duì)數(shù)組進(jìn)行處理等問(wèn)題,這里簡(jiǎn)單記錄遍歷數(shù)組的幾種方法,這篇文章主要給大家介紹了關(guān)于vue中數(shù)組常用的6種循環(huán)方法,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-03-03
基于Vue自定義指令實(shí)現(xiàn)按鈕級(jí)權(quán)限控制思路詳解
這篇文章主要介紹了基于vue自定義指令實(shí)現(xiàn)按鈕級(jí)權(quán)限控制,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧2018-05-05
Vue3解決ElementPlus自動(dòng)導(dǎo)入時(shí)ElMessage無(wú)法顯示的問(wèn)題
這篇文章主要介紹了Vue3解決ElementPlus自動(dòng)導(dǎo)入時(shí)ElMessage無(wú)法顯示的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
詳解利用eventemitter2實(shí)現(xiàn)Vue組件通信
這篇文章主要介紹了詳解利用eventemitter2實(shí)現(xiàn)Vue組件通信,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
vue webpack多頁(yè)面構(gòu)建的實(shí)例代碼
這篇文章主要介紹了vue webpack多頁(yè)面構(gòu)建的實(shí)例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2018-09-09
詳解keep-alive + vuex 讓緩存的頁(yè)面靈活起來(lái)
這篇文章主要介紹了keep-alive + vuex 讓緩存的頁(yè)面靈活起來(lái),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04

