Vue-接口数据请求封装

创建Api.js文件

// 配置API接口地址当前为测试
var root = "https://gbzhj.com/";
// 引用axios
var axios = require("axios");
// 自定义判断元素类型JS
function toType(obj) {
	return {}.toString
		.call(obj)
		.match(/\s([a-zA-Z]+)/)[1]
		.toLowerCase();
}
// 参数过滤函数
function filterNull(ofun) {
	for (var key in ofun) {
		if (ofun[key] === null) {
			delete ofun[key];
		}
		if (toType(ofun[key]) === "string") {
			ofun[key] = ofun[key].trim();
		} else if (toType(ofun[key]) === "object") {
			ofun[key] = filterNull(ofun[key]);
		} else if (toType(ofun[key]) === "array") {
			ofun[key] = filterNull(ofun[key]);
		}
	}
	return ofun;
}
/*
*/
function apiAxios(method, url, params, success, failure) {
	if (params) {
		params = filterNull(params);
	}
	axios({
			method: method,
			url: url,
			data: method === "POST" || method === "PUT" ? params : null,
			params: method === "GET" || method === "DELETE" ? params : null,
			baseURL: root,
			withCredentials: false,
			headers: { // 设置请求头
				token: "token"
			}
		})
		.then(function(res) {
			if (res.data.success === true) {
				if (success) {
					success(res.data);
				}
			} else {
				if (failure) {
					failure(res.data);
				} else {
					window.alert("error: " + JSON.stringify(res.data));
				}
			}
		})
		.catch(function(err) {
			let res = err.response;
			if (err) {
				window.alert("api error, HTTP CODE: " + res.status);
			}
		});
}

// 返回在vue模板中的调用接口
export default {
	// get请求
	get: function(url, params, success, failure) {
		return apiAxios("GET", url, params, success, failure);
	},
	// post请求
	post: function(url, params, success, failure) {
		return apiAxios("POST", url, params, success, failure);
	},
	put: function(url, params, success, failure) {
		return apiAxios("PUT", url, params, success, failure);
	},
	delete: function(url, params, success, failure) {
		return apiAxios("DELETE", url, params, success, failure);
	}
};

mian.js挂载

// 引用API文件
import api from "./api/Api.js";
// 将API方法绑定到全局
Vue.prototype.$api = api;

在Helloword.vue文件

methods: {
	// 请求地址
	slideImg() {
		console.log("测试")
		let paers = {}
		this.$api.get('api/banner', paers, res => {
		    console.log(res)
		})
	},
},

THE END
分享
二维码
< <上一篇
下一篇>>