vue-axios-plugin

2020-02-07 16:46 更新
Vuejs 項目的 axios 插件。


如何使用

通過 Script 標簽

<!-- 在 vue.js 之后引入 -->
<script src="https://unpkg.com/vue"></script><script src="https://unpkg.com/vue-axios-plugin"></script>

npm

首先通過 npm 安裝

npm install --save vue-axios-plugin

然后在入口文件配置如下:

import Vue from 'Vue';
import VueAxiosPlugin from 'vue-axios-plugin';

Vue.use(VueAxiosPlugin, {
    // 請求攔截處理
    reqHandleFunc: config => config,
    reqErrorFunc: error => Promise.reject(error),

    // 響應攔截處理
    resHandleFunc: response => response,
    resErrorFunc: error => Promise.reject(error)
});


配置參數(shù)

除了 axios 提供的默認請求配置, vue-axios-plugin 也提供了 request/response 攔截器配置,如下:

參數(shù)名 類型 默認值 描述
reqHandleFunc {Function} config => config 請求發(fā)起前的攔截處理函數(shù)
reqErrorFunc {Function} error => Promise.reject(error) 處理請求錯誤的函數(shù)
resHandleFunc {Function} response => response 響應數(shù)據(jù)處理函數(shù)
resErrorFunc {Function} error => Promise.reject(error) 響應錯誤處理函數(shù)


示例

在 Vue 組件上添加了$http 屬性,它默認提供 get 和 post 方法,使用如下:

this.$http.get(url, data, options).then(response => {
    console.log(response)
})
this.$http.post(url, data, options).then((response) => {
    console.log(response)
})

你也可以通過 this.$axios 來使用 axios 所有的 api 方法,如下:

this.$axios.get(url, data, options).then(response => {
    console.log(response);
})
this.$axios.post(url, data, options).then(response => {
    console.log(response);
})
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號