Axios ajax, show loading when making ajax request

前端 未结 3 858
遇见更好的自我
遇见更好的自我 2021-02-01 06:48

I\'m currently building a vue app and Im using axios. I have a loading icon which i show before making each call and hide after.

Im just wondering if there is a way to d

3条回答
  •  臣服心动
    2021-02-01 07:08

    For Nuxt with $axios plugin

    modules: ['@nuxtjs/axios', ...]

    plugins/axios.js

    export default ({ app, $axios ,store }) => {
      const token = app.$cookies.get("token")
      if (token) {
        $axios.defaults.headers.common.Authorization = "Token " + token
      }
      $axios.interceptors.request.use((config) => {
        store.commit("SET_DATA", { data:true, id: "loading" });
        return config;
      }, (error) => {
        return Promise.reject(error);
      });
    
      $axios.interceptors.response.use((response) => {
        store.commit("SET_DATA", { data:false, id: "loading" });
        return response;
      }, (error) => {
        return Promise.reject(error);
      })
    }
    

    store/index.js

    
    export default {
      state: () => ({
        loading: false
      }),
      mutations: {
        SET_DATA(state, { id, data }) {
          state[id] = data
        }
      },
      actions: {
        async nuxtServerInit({ dispatch, commit }, { app, req , redirect }) {
          const token = app.$cookies.get("token")
          if (token) {
            this.$axios.defaults.headers.common.Authorization = "Token " + token
          }
          let status = await dispatch("authentication/checkUser", { token })
          if(!status) redirect('/aut/login')
        }
      }
    }
    

    This example is accompanied by a token check with $axios and store

提交回复
热议问题