1添加一个新的 http.js文件 封装axios
引入axios
//引入Axios import axios from 'axios'
定义一个根地址
//视你自己的接口地址而定 var root2 = 'http://121.4.63.196:8520/api'
定义个小函数来统一参数格式(可写可不写,自己随意)
//参数过滤(去空白) function filterNull(o) { for (var key in o) { if (o[key] === null) { delete o[key] } //字符串,对象,数组 if (typeof (o[key]) === 'string') { o[key] = o[key].trim() } else if (typeof (o[key] === 'object')) { alert(o[key]); o[key] = filterNull(o[key]) } else if (typeof (o[key]) === 'array') { o[key] = filterNull(o[key]) } } return o }参数过滤(去空白)
接口处理:重头戏
//接口处理函数 function apiAxios(method, url, params, success) { //整理参数 if (params) { params = filterNull(params) console.log(params); } axios({ method: method, url: url, data: method === 'post' || method === 'put' ? params : null, params: method === 'get' || method === 'delete' ? params : null, headers: { //'Content-Type':'application/json' }, baseURL: root2, withCredentials: false }).then(function (res) { if (res.State && res.Code) {success(res.data)
} }).catch(function (error) { let res = error.response if (error) { console.log('API错误:' + res.State); } }) }
导出给vue组件使用
//返回在vue模板中调用的接口 export default ({ get: function (url, params, success, failure) { return apiAxios('get', url, params, success, failure); }, 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); } })
main.js里面如何使用:
//引入接口文件 import api from './api/http.js' var app=createApp(App) app.use(routers)app.mount('#app')
//绑定给全局使用 $api可以随便定义 例如 $http $a $b 随喜好 app.config.globalProperties.$api=api
app.vue里面使用
this.$api.post('/AutoCode/SendEmail163', { 'email': this.email },r=>{ this.email2=r.message });
标签:function,axios,封装,success,url,failure,params,key,vue3 From: https://www.cnblogs.com/zhang-3/p/16913968.html