[TOC]
>[success] # 封裝axios
1. 首先在 **src文件夾** 下的 **lib文件夾** 中創建 **axios.js**
**src/lib/axios.js**
~~~
import axios from 'axios'
import { baseURL } from '@/config'
import { getToken } from '@/lib/util'
class HttpRequest {
constructor(baseUrl = baseURL){ // baseUrl = baseURL 是ES6的默認值寫法等同于 baseUrl = baseUrl || baseURL
this.baseUrl = baseUrl // this指向創建的實例,當你使用new HttpRequest創建實例時候,它會把this中定義的變量返回給你
this.queue = {} // 創建隊列,每次請求都會向里面添加一個key:value,請求成功后就會去掉這個key:value,直到this.queue中沒有屬性值時,loading關閉
}
/**
* 默認options配置
*/
getInsideConfig(){
const config = {
baseURL: this.baseUrl,
headers: {
//
}
}
return config
}
distroy (url) {
delete this.queue[url]
if (!Object.keys(this.queue).length) {
// Spin.hide()
}
}
/**
* 攔截器
* @param {Object} instance - 通過axios創建的實例
* @param {String} url - 接口地址
*/
interceptors(instance, url){
/**
* 請求攔截器
* @param {Function} config - 請求前的控制
* @param {Function} error - 出現錯誤的時候會提供一個錯誤信息
*/
instance.interceptors.request.use(config => {
// 添加全局的Lodaing...
if(!Object.keys(this.queue).length){
// Spin.show()
}
this.queue[url] = true
config.headers['Authorization'] = getToken()
return config
}, error => {
return Promise.reject(error)
})
/**
* 響應攔截器
* @param {Function} res - 服務端返回的東西
* @param {Function} error - 出現錯誤的時候會提供一個錯誤信息
*/
instance.interceptors.response.use(res => {
this.distroy(url) // 關閉全局的Lodaing...
const { data } = res
return data
}, error => {
this.distroy(url) // 關閉全局的Lodaing...
return Promise.reject(error.response.data)
})
}
request(options){
const instance = axios.create()
options = Object.assign(this.getInsideConfig(), options) // Object.assign會將2個對象合并成1個對象,相同屬性值會被后者覆蓋
this.interceptors(instance, options.url) // 攔截器
return instance(options)
}
}
export default HttpRequest
~~~
**constructor方法** 是 **每一個類必須有的方法** ,如果我們不定義這個 **constructor方法** , **class類** 會默認添加一個 **空的constructor方法(例如:constructor(){})** ,在 **constructor方法** 中可以 **接收傳入的參數** , 在我們 **創建實例 new HttpRequest('參數')** 時候可以 **在括號內傳入參數** , 然后我們可以在 **constructor方法** 中 **對參數做一些操作** 。
2. 上面把 **baseUrl** 抽離到了 **config文件夾** 里的 **index.js 全局變量** 中
**src/config/index.js**
~~~
// 如果當前是生產環境用生產環境地址,如果是開發環境并且在vue.config.js中配置了代理,就用空字符串【''】,如果未配置代理就用開發環境地址
export const baseURL= process.env.NODE_ENV === 'production' ? 'http://production.com' : 'http://develop.com'
~~~
>[success] ## 使用方法
1. 在 **api文件夾** 中創建 **index.js**
**src/api/index.js**
~~~
import HttpRequest from '@/lib/axios'
const axios = new HttpRequest()
export default axios
~~~
在使用時候:我們創建一個儲存用戶接口的 **uesr.js** 文件
**src/api/user.js**
~~~
import axios from './index'
// 獲取用戶信息接口
export const getUserInfo = ({ userId }) => {
return axios.request({
url: '/index/getUserInfo',
method: 'post',
data: {
userId
}
})
}
~~~
然后在 **Home.vue** 頁面組件中這樣 **調用接口**
**Home.vue**
~~~
<template>
<div>
<button @click="getInfo">請求數據</button>
</div>
</template>
<script>
import { getUserInfo } from '@/api/user'
export default {
methods: {
getInfo(){
getUserInfo({ userId: 21 }).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
}
}
</script>
~~~
- vue 26課
- Vue-cli3.0項目搭建
- Vue-ui 創建cli3.0項目
- Vue-ui 界面詳解
- 項目目錄詳解
- public文件夾
- favicon.ico
- index.html
- src文件夾
- api文件夾
- assets文件夾
- components文件夾
- config文件夾
- directive文件夾
- lib文件夾
- mock文件夾
- mock簡明文檔
- router文件夾
- store文件夾
- views文件夾
- App.vue
- main.js
- .browserslistrc
- .editorconfig
- .eslintrc.js
- .gitignore
- babel.config.js
- package-lock.json
- package.json
- postcss.config.js
- README.en.md
- README.md
- vue.config.js
- Vue Router
- 路由詳解(一)----基礎篇
- 路由詳解(二)----進階篇
- Vuex
- Bus
- Vuex-基礎-state&getter
- Vuex-基礎-mutation&action/module
- Vuex-進階
- Ajax請求
- 解決跨域問題
- 封裝axios
- Mock.js模擬Ajax響應
- 組件封裝
- 從數字漸變組件談第三方JS庫使用
- 從SplitPane組件談Vue中如何【操作】DOM
- 渲染函數和JSX快速掌握
- 遞歸組件的使用
- 登陸/登出以及JWT認證
- 響應式布局
- 可收縮多級菜單的實現
- vue雜項
- vue遞歸組件
- vue-cli3.0多環境打包配置
- Vue+Canvas實現圖片剪切
- vue3系統入門與項目實戰
- Vue語法初探
- 初學編寫 HelloWorld 和 Counter
- 編寫字符串反轉和內容隱藏功能
- 編寫TodoList功能了解循環與雙向綁定
- 組件概念初探,對 TodoList 進行組件代碼拆分
- Vue基礎語法
- Vue 中應用和組件的基礎概念
- 理解 Vue 中的生命周期函數
- 常用模版語法講解
- 數據,方法,計算屬性和偵聽器
- 樣式綁定語法
- 條件渲染
- 列表循環渲染
- 事件綁定
- 表單中雙向綁定指令的使用
- 探索組件的理念
- 組件的定義及復用性,局部組件和全局組件
- 組件間傳值及傳值校驗
- 單向數據流的理解
- Non-Props 屬性是什么
- 父子組件間如何通過事件進行通信
- 組件間雙向綁定高級內容
- 使用匿名插槽和具名插槽解決組件內容傳遞問題
- 作用域插槽
- 動態組件和異步組件
- 基礎語法知識點查缺補漏
- Vue 中的動畫
- 使用 Vue 實現基礎的 CSS 過渡與動畫效果
- 使用 transition 標簽實現單元素組件的過渡和動畫效果
- 組件和元素切換動畫的實現
- 列表動畫
- 狀態動畫
- Vue 中的高級語法
- Mixin 混入的基礎語法
- 開發實現 Vue 中的自定義指令
- Teleport 傳送門功能
- 更加底層的 render 函數
- 插件的定義和使用
- 數據校驗插件開發實例
- Composition API
- Setup 函數的使用
- ref,reactive 響應式引用的用法和原理
- toRef 以及 context 參數
- 使用 Composition API 開發TodoList
- computed方法生成計算屬性
- watch 和 watchEffect 的使用和差異性
- 生命周期函數的新寫法
- Provide,Inject,模版 Ref 的用法
- Vue 項目開發配套工具講解
- VueCLI 的使用和單文件組件
- 使用單文件組件編寫 TodoList
- Vue-Router 路由的理解和使用
- VueX 的語法詳解
- CompositionAPI 中如何使用 VueX
- 使用 axios 發送ajax 請求
- Vue3.0(正式版) + TS
- 你好 Typescript: 進入類型的世界
- 什么是 Typescript
- 為什么要學習 Typescript
- 安裝 Typescript
- 原始數據類型和 Any 類型
- 數組和元組
- Interface- 接口初探
- 函數
- 類型推論 聯合類型和 類型斷言
- class - 類 初次見面
- 類和接口 - 完美搭檔
- 枚舉(Enum)
- 泛型(Generics) 第一部分
- 泛型(Generics) 第二部分 - 約束泛型
- 泛型第三部分 - 泛型在類和接口中的使用
- 類型別名,字面量 和 交叉類型
- 聲明文件
- 內置類型
- 總結