生活随笔
收集整理的這篇文章主要介紹了
vue项目请求封装;axios封装使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
vue項目,封裝axios請求方式和響應狀態碼;以及接口的api封裝;
目錄結構:
1.具體在src/utils/request.js下封裝axios:
①引入axios和router
②引入element-ui是為了用提示組件 和加載組件(可選擇去掉)
③根據請求攔截器的config配置請求頭
④根據響應攔截器的不同狀態碼做不同處理(狀態碼需要自己根據項目修改)
簡單的request.js封裝點擊這里,沒有封裝狀態碼和提示–可自己配
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
: "網絡請求不存在",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("登錄超時或身份失效,請重新登錄!", "警告", {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
: "請求超時",type
: "error",duration
: 3 * 1000});break;case 700:Message
.closeAll();Message({message
: "網絡中斷",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) ; 下方的函數方法都是可以接受三個參數的 分別是 地址 參數 配置 三個參數可以由組件內使用的函數function傳入
③在組件內使用,接受傳遞的參數和配置(詳見test.vue組件內的方法)
以下get post put delete 請求均有;且對于不同的請求需要配置的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在組件內使用接口方法:
①引入way.js內的接口方法:
②傳遞參數
③通過.then()獲取使用
<template
><div
>接口返回參數
<div
>{{ data
}}</div
><!-- <el
-input v
-model
="input" placeholder
="請輸入內容" /> --><button @click
="getlistRequest">get 獲取列表
</button
><button @click
="getClassRequest">get動態參數 獲取班級
</button
><button @click
="btnRequest">post點擊獲取url
</button
><button @click
="getKnowledgeRequest">post傳參獲取知識點
</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
= '學情報告.xlsx'a
.click()window
.URL.revokeObjectURL(blob
)a
.remove()})}}
}
</script
><style
>
</style
>
4.頁面和接口展示:
成功200:
需要配置config的下載:
請求失敗提示:
總結
以上是生活随笔為你收集整理的vue项目请求封装;axios封装使用的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。