Vuejs 項目的 axios 插件。
<!-- 在 vue.js 之后引入 -->
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-axios-plugin"></script>
首先通過 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)
});
除了 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);
})
更多建議: