axios项目二次封装
Posted 魔都叛徒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了axios项目二次封装相关的知识,希望对你有一定的参考价值。
import axios from ‘axios‘ import qs from ‘qs‘ const baseURL = "http://10.4.108.117:8081/" exports.install = function (Vue, options) { Vue.prototype.get = function (url, data, success) { axios({ url: baseURL + url, params: data, headers: { "token": localStorage.getItem("token") } }).then((respose) => { if (respose.status == 200) { var resultMap = respose.data; if (resultMap) { if (!resultMap.code) { success(resultMap); } else { if (resultMap.code == 200) { success(resultMap.data); } else { if (resultMap.msg) { let errorMsg = resultMap.msg.replace(/d+/, "").replace("|", ""); this.$Message.error(errorMsg); let _this = this; if (errorMsg == "帐号未登录") { setTimeout(function () { // 退出登录 _this.$store.commit(‘logout‘, this); _this.$store.commit(‘clearOpenedSubmenu‘); _this.$router.push({ name: ‘login‘ }); }, 300); } } } } } } else { this.$Message.error(respose.statusText); } }).catch((error) => { }) }; Vue.prototype.post = function (url, data, success) { axios.post(baseURL + url, qs.stringify(data), { headers: { "token": localStorage.getItem("token") } }).then((respose) => { if (respose.status == 200) { var resultMap = respose.data; if (resultMap) { if (resultMap.code == 200) { success(resultMap.data) } else { if (resultMap.msg) { let errorMsg = resultMap.msg.replace(/d+/, "").replace("|", ""); this.$Message.error(errorMsg); let _this; if (errorMsg == "帐号未登录") { setTimeout(function () { // 退出登录 _this.$store.commit(‘logout‘, this); _this.$store.commit(‘clearOpenedSubmenu‘); _this.$router.push({ name: ‘login‘ }); }, 300); } } } } } else { this.$Message.error(respose.statusText); } }).catch((error) => { console.log(error) }) }; Vue.prototype.postHandle = function (url, data, success) { axios.post(baseURL + url, qs.stringify(data)).then((respose) => { if (success) { success(respose) } }).catch((error) => { console.log(error) }) }; Vue.prototype.getBaseUrl = function () { return baseURL; } Vue.prototype.getUrlParameter = function (obj) { let _paramter = "?token=" + localStorage.getItem("token"); if (obj) { Object.keys(obj).forEach(function (key) { if (typeof obj[key] == "number" || obj[key]) { _paramter = _paramter + "&" + key + "=" + obj[key]; } }); } return _paramter; } }
以上是关于axios项目二次封装的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段14——Vue的axios网络请求封装
VSCode自定义代码片段14——Vue的axios网络请求封装