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)文章
Vue使用Tinymce富文本自定義toolbar按鈕的實(shí)踐
本文主要介紹了Vue使用Tinymce富文本自定義toolbar按鈕,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12
vue-router解決相同路徑跳轉(zhuǎn)報(bào)錯(cuò)的問(wèn)題
這篇文章主要介紹了vue-router解決相同路徑跳轉(zhuǎn)報(bào)錯(cuò)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
vue 中使用 watch 出現(xiàn)了如下的報(bào)錯(cuò)的原因分析
這篇文章主要介紹了vue 中使用 watch 出現(xiàn)了如下的報(bào)錯(cuò)信息的原因分析及解決方法,本文附有代碼解決方案,非常不錯(cuò),需要的朋友可以參考下2019-05-05
vuedraggable+element ui實(shí)現(xiàn)頁(yè)面控件拖拽排序效果
這篇文章主要為大家詳細(xì)介紹了vuedraggable+element ui實(shí)現(xiàn)頁(yè)面控件拖拽排序效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12
Vue中Number方法將字符串轉(zhuǎn)換為數(shù)字的過(guò)程
這篇文章主要介紹了Vue中Number方法將字符串轉(zhuǎn)換為數(shù)字,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
Vue項(xiàng)目之安裝引入使用vconsole方式(生產(chǎn)環(huán)境不顯示)
在Vue2開(kāi)發(fā)中,引入vConsole可以為移動(dòng)端提供類似瀏覽器F12的調(diào)試工具,支持查看日志、網(wǎng)絡(luò)請(qǐng)求等功能,vConsole是一個(gè)輕量、可拓展的前端調(diào)試面板,與框架無(wú)關(guān),適用于多種前端框架,安裝方法包括npm和CDN兩種,可根據(jù)項(xiàng)目環(huán)境配置是否顯示調(diào)試面板2024-10-10

