我正在使用Vue CLI加载Axios的实例属性。我添加了几个拦截器,我希望能够在Vue组件内部使用Axios实例时关闭它们。
在文档中,Axios建议您只标记拦截器,然后通过名称eject
。
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
所以我遇到的问题是,我无法弄清楚我可以将拦截器命名为谁以用于组件。
这是我的设置:
API-client.js
import axios from 'axios'
var client = axios.create({
baseURL: process.env.API_DOMAIN,
headers: { Accept: 'application/json' }
})
var unauthorizedInterceptor = client.interceptors.response.use(function (response) {
return response
}, function (error) {
...
return Promise.reject(error)
})
export default client
main.js
import Vue from 'vue'
import apiClient from './api-client'
Vue.prototype.$apiClient = apiClient
new Vue({
el: '#app',
...
})
component.js
<template>
...
</template>
<script>
export default {
data () {
return {
username: null,
email: null,
firstName: null,
lastName: null
}
},
methods: {
updateAccount () {
var self = this
var data = {
username: this.username,
email: this.email,
first_name: this.firstName,
last_name: this.lastName
}
self.$apiClient`enter code here`.interceptors.request.eject(unauthorizedInterceptor) // Remove interceptor here.
self.$apiClient.patch('/me')
.then(function () {
...
})
.catch(function () {
...
})
}
}
}
</script>
如何命名拦截器以在组件级别弹出它?
答案 0 :(得分:1)
从您的api-client.js
导出拦截器并将其导入您要将其弹出的位置。
<强> API-client.js 强>
export let unauthorizedInterceptor = ...
export default client
<强> component.js 强>
import { unauthorizedInterceptor } from "./api-client"
...
self.$http.interceptors.request.eject(unauthorizedInterceptor)
您可能还希望导出拦截器功能本身,以便在需要时可以将其添加回来。
或者导出一个或多个可以为您进行此管理的功能。
<强> API-client.js 强>
let unauthorizedInterceptor
export function removeUnauthorizedInterceptor() {
axios.interceptors.request.eject(unauthorizedInterceptor)
}
export function addUnauthorizedInterceptor(){
unauthorizedInterceptor = axios.interceptors.response.use(...)
}
<强> component.js 强>
import { removeUnauthorizedInterceptor} from "./api-client"
removeUnauthorizedInterceptor()