vue 封装 js 方法
一、安装 axios
并引入:
Axios 中文说明
- 安装axios:
npm install axios
- 因为基本上全局都会使用到
axios
方法,所以在main.js
中引入:
import axios from 'axios';
Vue.prototype.$axios = axios //全局注册,使用方法为:this.$axios
二、新建文件,封装 axios
1. 在src下新建一个 api
文件夹,并在 api
下新建 ajax.js
和index.js
;
因为要在全局上使用,且引入时地址想要少写一个 index.js
,所以 index.js
写请求接口,ajax.js
写请求拦截
2. ajax.js
import axios from 'axios'
import router from '@/router'
import store from '@/store'
import {Message,MessageBox,Loading} from 'element-ui';
import {getCookie} from '@/filters/cookie';let loading = null;//请求拦截器
axios.interceptors.request.use(function (config) {// 在发送请求之前做些什么(将数据发送给后台时的请求操作,可以给请求头添加token等信息)loading = Loading.service({lock: true,text: 'Loading',spinner: 'el-icon-loading',background: 'rgba(0, 0, 0, 0.7)'});// setTimeout(() => {// loading.close();// }, 2000);//判断是不是登录接口,如果不是,则请求参数添加:token/userCode字段var reg = /userLogin$/;if( !reg.test(config.url) ){if( getCookie("token") ){ //token是否存在,,导入功能也加了请求头config.headers.accessToken = getCookie("token");config.headers.clientType = 1;} else {config.headers.accessToken = "默认的token,防止测试出错"; //techsun的// config.headers.accessToken = "E9922E7DFC5B013D2D9BC00348DF12132D6310C3DCCAD9E9A81CF4AD1E69704C" //TCtechsunconfig.headers.clientType = 1;}} return config;
}, function (error) {// 对请求错误做些什么return Promise.reject(error);
});// 添加响应拦截器
axios.interceptors.response.use(function (response) {if(loading !== null) {loading.close()loading = null;}// 对响应数据做点什么if(response.data.code === "0000" && response.status === 200){return response.data;} //比如二进制流else if(!response.data.code && response.status === 200){console.log("axios配置",response)return response;}else {//0001:系统异常,请联系管理员;0002:没有查询到结果Message.error(response.data.msg);}
}, function (error) {// 对响应错误做点什么if(loading !== null) {loading.close()loading = null;}return Promise.reject(error);
});
export default axios;
3. index.js
import './ajax'
const BASE_URL = '后台ip'; //测试--外网
let aaabbb = { //记住aaabbb这个变量名,使用时会用到login: BASE_URL + 'userLogin', //登录statisticsByLabelType: BASE_URL + '接口名称1', //记住前面的属性名称,在使用会用到statisticsByProduct: BASE_URL + '接口名称2', //按品种统计的出库数量
}
export default{aaabbb}
三、引入封装的方法,并使用
1. 在 main.js 中引入
//axios
import axios from "axios";
Vue.prototype.$axios = axios;
import api from '@/components/api' //引入接口,index.js可以省略
// console.log(api.smoke)
Vue.prototype.$api = api.aaabbb;
2. 使用
this.$axios.post(statisticsByLabelType, this.params)
.then(res=>{//请求成功的操作
}).catch(err=>{})
参考:
axios请求成功之前加载loading,封装axios请求