封装 axios 请求
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                封装 axios 请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                vue 封裝 js 方法
一、安裝 axios 并引入:
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請求
總結
以上是生活随笔為你收集整理的封装 axios 请求的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 使用echarts时,鼠标首次移入屏幕会
- 下一篇: 移动端 flexible.js 布局详解
