Axios拦截器不会更新Vuex状态

时间:2019-03-22 01:50:20

标签: javascript axios nuxt.js

我想通过使用axios拦截器来显示微调器,方法是根据请求设置true的状态,响应时设置false的状态。

services / apiClient.js

import store from '../store/index';

axiosClient.interceptors.request.use(function (config) {
  store().commit('SET_LOADING_STATUS', true);
  return config;
}, function (error) {
  return Promise.reject(error);
});

axiosClient.interceptors.response.use(function (response) {
  store().commit('SET_LOADING_STATUS', false);
  if (response.data.status.code != 200) {
    throw { message: response.data.status.errorDetail };
  } else {
    return response;
  }
}, function (error) {
  return Promise.reject(error);
});

然后在我的Vuex store / index.js

import Vuex from 'vuex';
    const store = () => {
  return new Vuex.Store({
    state: {
      isLoading: null
    },
    mutations: {
      SET_LOADING_STATUS(state, bool) {
        console.log(bool);
        state.isLoading = bool;
      }
    },
    actions: {
      setLoadingStatus({ commit }, bool) {
        commit('SET_LOADING_STATUS', bool);
      }
    },
    getters: {
      loadedState(state) {
        return state.isLoading;
      }
    }
  });
};

export default store;

我从console.log获取truefalse

但是当我从 layouts / default.vue

<template>
 <div>
   {{isLoading}}
   <nuxt/>
 </div>
</template>

<script>  
  export default {
    computed: {
      isLoading() {
       console.log(this.$store.getters.loadedState);
       return this.$store.getters.loadedState;
      }
    }
  }
</script>

isLoading计算的属性返回null,我希望它应该返回false,因为在axios的响应拦截器上,我将其设置为false

在我的 index.vue 中,我触发了来自axios的请求

<template>
  <div> 
    <h1> Index Page </h1>
  </div>
</template>

<script>
 export default {
   created() {
     this.$store.dispatch('getUsers', this); // this will trigger API call
   }
 }
</script>

0 个答案:

没有答案