溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Vue中對axios進(jìn)行封裝

發(fā)布時間:2021-03-01 15:48:46 來源:億速云 閱讀:193 作者:戴恩恩 欄目:web開發(fā)

本文章向大家介紹怎么在Vue中對axios進(jìn)行封裝的基本知識點(diǎn)總結(jié)和需要注意事項(xiàng),具有一定的參考價值,需要的朋友可以參考一下。

Vue的優(yōu)點(diǎn)

Vue具體輕量級框架、簡單易學(xué)、雙向數(shù)據(jù)綁定、組件化、數(shù)據(jù)和結(jié)構(gòu)的分離、虛擬DOM、運(yùn)行速度快等優(yōu)勢,Vue中頁面使用的是局部刷新,不用每次跳轉(zhuǎn)頁面都要請求所有數(shù)據(jù)和dom,可以大大提升訪問速度和用戶體驗(yàn)。

  • 實(shí)現(xiàn)的功能

  • 統(tǒng)一捕獲接口報(bào)錯 : 用的axios內(nèi)置的攔截器

  • 彈窗提示: 引入 Element UI 的 Message 組件

  • 報(bào)錯重定向: 路由鉤子

  • 基礎(chǔ)鑒權(quán): 服務(wù)端過期時間戳和token,還有借助路由的鉤子

  • 表單序列化: 我這邊直接用 qs (npm模塊),你有時間也可以自己寫

用法及封裝

用法

// 服務(wù)層 , import默認(rèn)會找該目錄下index.js的文件,這個可能有小伙伴不知道
// 可以去了解npm的引入和es6引入的理論概念
import axiosPlugin from "./server"; 
Vue.use(axiosPlugin);

對axios的封裝(AXIOS: index.js )

import axios from "axios";
import qs from "qs";
import { Message } from "element-ui";
import router from "../router";
const Axios = axios.create({
 baseURL: "/", // 因?yàn)槲冶镜刈隽朔聪虼?
 timeout: 10000,
 responseType: "json",
 withCredentials: true, // 是否允許帶cookie這些
 headers: {
  "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
 }
});
//POST傳參序列化(添加請求攔截器)
Axios.interceptors.request.use(
 config => {
  // 在發(fā)送請求之前做某件事
  if (
   config.method === "post"
  ) {
   // 序列化
   config.data = qs.stringify(config.data);
   // 溫馨提示,若是貴公司的提交能直接接受json 格式,可以不用 qs 來序列化的
  }
  // 若是有做鑒權(quán)token , 就給頭部帶上token
  // 若是需要跨站點(diǎn),存放到 cookie 會好一點(diǎn),限制也沒那么多,有些瀏覽環(huán)境限制了 localstorage 的使用
  // 這里localStorage一般是請求成功后我們自行寫入到本地的,因?yàn)槟惴旁趘uex刷新就沒了
  // 一些必要的數(shù)據(jù)寫入本地,優(yōu)先從本地讀取
  if (localStorage.token) {
   config.headers.Authorization = localStorage.token;
  }
  return config;
 },
 error => {
  // error 的回調(diào)信息,看貴公司的定義
  Message({
   // 餓了么的消息彈窗組件,類似toast
   showClose: true,
   message: error && error.data.error.message,
   type: 'error'
  });
  return Promise.reject(error.data.error.message);
 }
);
//返回狀態(tài)判斷(添加響應(yīng)攔截器)
Axios.interceptors.response.use(
 res => {
  //對響應(yīng)數(shù)據(jù)做些事
  if (res.data && !res.data.success) {
   Message({
    // 餓了么的消息彈窗組件,類似toast
    showClose: true,
    message: res.data.error.message.message
     ? res.data.error.message.message
     : res.data.error.message,
    type: "error"
   });
   return Promise.reject(res.data.error.message);
  }
  return res;
 },
 error => {
  // 用戶登錄的時候會拿到一個基礎(chǔ)信息,比如用戶名,token,過期時間戳
  // 直接丟localStorage或者sessionStorage
  if (!window.localStorage.getItem("loginUserBaseInfo")) {
   // 若是接口訪問的時候沒有發(fā)現(xiàn)有鑒權(quán)的基礎(chǔ)信息,直接返回登錄頁
   router.push({
    path: "/login"
   });
  } else {
   // 若是有基礎(chǔ)信息的情況下,判斷時間戳和當(dāng)前的時間,若是當(dāng)前的時間大于服務(wù)器過期的時間
   // 乖乖的返回去登錄頁重新登錄
   let lifeTime =
    JSON.parse(window.localStorage.getItem("loginUserBaseInfo")).lifeTime *
    1000;
   let nowTime = new Date().getTime(); // 當(dāng)前時間的時間戳
   console.log(nowTime, lifeTime);
   console.log(nowTime > lifeTime);
   if (nowTime > lifeTime) {
    Message({
     showClose: true,
     message: "登錄狀態(tài)信息過期,請重新登錄",
     type: "error"
    });
    router.push({
     path: "/login"
    });
   } else {
    // 下面是接口回調(diào)的satus ,因?yàn)槲易隽艘恍╁e誤頁面,所以都會指向?qū)?yīng)的報(bào)錯頁面
    if (error.response.status === 403) {
     router.push({
      path: "/error/403"
     });
    }
    if (error.response.status === 500) {
     router.push({
      path: "/error/500"
     });
    }
    if (error.response.status === 502) {
     router.push({
      path: "/error/502"
     });
    }
    if (error.response.status === 404) {
     router.push({
      path: "/error/404"
     });
    }
   }
  }
  // 返回 response 里的錯誤信息
  let errorInfo = error.data.error ? error.data.error.message : error.data;
  return Promise.reject(errorInfo);
 }
);
// 對axios的實(shí)例重新封裝成一個plugin ,方便 Vue.use(xxxx)
export default {
 install: function(Vue, Option) {
  Object.defineProperty(Vue.prototype, "$http", { value: Axios });
 }
};

路由鉤子的調(diào)整(Router: index.js )

import Vue from "vue";
import Router from "vue-router";
import layout from "@/components/layout/layout";
// 版塊有點(diǎn)多,版塊獨(dú)立路由管理,里面都是懶加載引入
import customerManage from "./customerManage"; // 客戶管理
import account from "./account"; //登錄
import adManage from "./adManage"; // 廣告管理
import dataStat from "./dataStat"; // 數(shù)據(jù)統(tǒng)計(jì)
import logger from "./logger"; // 日志
import manager from "./manager"; // 管理者
import putonManage from "./putonManage"; // 投放管理
import error from "./error"; // 服務(wù)端錯誤
import { Message } from "element-ui";
Vue.use(Router);
// 請?zhí)^這一段,看下面的
const router = new Router({
 hashbang: false,
 mode: "history",
 routes: [
  {
   path: "/",
   redirect: "/adver",
   component: layout,
   children: [
    ...customerManage,
    ...adManage,
    ...dataStat,
    ...putonManage,
    ...manager,
    ...logger
   ]
  },
  ...account,
  ...error
 ]
});
// 路由攔截
// 差點(diǎn)忘了說明,不是所有版塊都需要鑒權(quán)的
// 所以需要鑒權(quán),我都會在路由meta添加添加一個字段requireLogin,設(shè)置為true的時候
// 這貨就必須走鑒權(quán),像登錄頁這些不要,是可以直接訪問的!!!
router.beforeEach((to, from, next) => {
 if (to.matched.some(res => res.meta.requireLogin)) {
  // 判斷是否需要登錄權(quán)限
  if (window.localStorage.getItem("loginUserBaseInfo")) {
   // 判斷是否登錄
   let lifeTime =
    JSON.parse(window.localStorage.getItem("loginUserBaseInfo")).lifeTime *
    1000;
   let nowTime = (new Date()).getTime(); // 當(dāng)前時間的時間戳
   if (nowTime < lifeTime) {
    next();
   } else {
    Message({
     showClose: true,
     message: "登錄狀態(tài)信息過期,請重新登錄",
     type: "error"
    });
    next({
     path: "/login"
    });
   }
  } else {
   // 沒登錄則跳轉(zhuǎn)到登錄界面
   next({
    path: "/login"
   });
  }
 } else {
  next();
 }
});
export default router;

axios可配置的一些選項(xiàng),其他的具體看官網(wǎng)說明哈

export default {
 // 請求地址
 url: "/user",
 // 請求類型
 method: "get",
 // 請根路徑
 baseURL: "http://www.mt.com/api",
 // 請求前的數(shù)據(jù)處理
 transformRequest: [function(data) {}],
 // 請求后的數(shù)據(jù)處理
 transformResponse: [function(data) {}],
 // 自定義的請求頭
 headers: { "x-Requested-With": "XMLHttpRequest" },
 // URL查詢對象
 params: { id: 12 },
 // 查詢對象序列化函數(shù)
 paramsSerializer: function(params) {},
 // request body
 data: { key: "aa" },
 // 超時設(shè)置s
 timeout: 1000,
 // 跨域是否帶Token
 withCredentials: false,
 // 自定義請求處理
 adapter: function(resolve, reject, config) {},
 // 身份驗(yàn)證信息
 auth: { uname: "", pwd: "12" },
 // 響應(yīng)的數(shù)據(jù)格式 json / blob /document /arraybuffer / text / stream
 responseType: "json",
 // xsrf 設(shè)置
 xsrfCookieName: "XSRF-TOKEN",
 xsrfHeaderName: "X-XSRF-TOKEN",

 // 下傳和下載進(jìn)度回調(diào)
 onUploadProgress: function(progressEvent) {
  Math.round(progressEvent.loaded * 100 / progressEvent.total);
 },
 onDownloadProgress: function(progressEvent) {},

 // 最多轉(zhuǎn)發(fā)數(shù),用于node.js
 maxRedirects: 5,
 // 最大響應(yīng)數(shù)據(jù)大小
 maxContentLength: 2000,
 // 自定義錯誤狀態(tài)碼范圍
 validateStatus: function(status) {
  return status >= 200 && status < 300;
 },
 // 用于node.js
 httpAgent: new http.Agent({ keepAlive: true }),
 httpsAgent: new https.Agent({ keepAlive: true }),

 // 用于設(shè)置跨域請求代理
 proxy: {
  host: "127.0.0.1",
  port: 8080,
  auth: {
   username: "aa",
   password: "2123"
  }
 },
 // 用于取消請求
 cancelToken: new CancelToken(function(cancel) {})
};

以上就是小編為大家?guī)淼脑趺丛赩ue中對axios進(jìn)行封裝的全部內(nèi)容了,希望大家多多支持億速云!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI