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)
		})
	},
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值