edison xue
edison xue

Reputation: 1331

How can I use the axios.interceptor in a right way?

I use vue-cli and this is part of my main.js.In Vue's single File components' structure, I use axios to replace the ajax.

import Vue from 'vue'
import App from './App'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Vue.config.productionTip = false

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

It makes axios available in every SFC by referring (this.axios). But when I try to use axios.interceptor, I come across an annoying problem. I want to set axios.interceptor.request and axios.interceptor.reponse for the whole project. however, I can only use this.axios.interceptor.request in a Single File Component and it only work in this file. This is the part code of App.js.

  methods: {
    // interceptor
    setAxiosInterceptor () {
      this.axios.interceptors.request.use(config => {
        this.cover = true
        return config
      }, error => Promise.reject(error)
      )
      this.axios.interceptors.response.use(response => {
        this.cover = false
        return response
      }, error => {
        this.cover = false
        return Promise.reject(error)
      })
    },

I have to set this.axios.interceptor in every SFC. So how can I set the axios.interceptor for the whole project and make it available in every SFC.

Upvotes: 1

Views: 5500

Answers (1)

SlowTurtle
SlowTurtle

Reputation: 96

In a Vue component creating the method setAxiosInterceptor() has scope local to that component. A root component method could be exposed to children components using vm.$root alias.

A better approach in this case is not to create the method setAxiosInterceptor() but use the Vue component created: lifecycle hook

To set axios.interceptor.request and axios.interceptor.reponse globally adjust App.vue to

<script>
import axios from "axios";
export default {
    ...
    
    methods: {},
    created: function () {

    axios.interceptors.request.use(config => {
        this.cover = true
        return config
      }, error => Promise.reject(error)
      )
      axios.interceptors.response.use(response => {
        this.cover = false
        return response
      }, error => {
        this.cover = false
        return Promise.reject(error)
      })
    }

    ...
};
</script>

The following lines in main.js are not required to achieve this particular outcome.

import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

Upvotes: 4

Related Questions