Vuex商店未定义

时间:2017-12-16 18:58:34

标签: javascript vue.js vuex

我正在为我的应用程序使用vuex,axios,我想在axios启动中使用getter来传递基本身份验证。这是我的axios init(http-common.js):

import m1 from './modules/m1'
import m2 from './modules/m2'
import authentification from './modules/authentification'

Vue.use(Vuex)
export default new Vuex.Store({
  modules: {
    authentification,
    m1,
    m2
  }
})

当我调试我的应用程序时,我发现存储未定义。有人可以解释我做错了什么吗?存储本身在所有组件中都可以正常工作。

我的商店有几个模块和那些模块。 store index.js:

import HTTP from '@/common/http-common'  
.....
const actions = {
  action ({commit}) {
        HTTP.get('item')
            .then(response => {
              commit('MUTATION', {response})
            })
  }
}
.....
export default {
  state,
  getters,
  actions,
  mutations
}

模块使用axios init函数调用REST api,即:

import * as types from '../mutation-types'

const state = {
  isLoggedIn: !!localStorage.getItem('auth'),
  auth: JSON.parse(localStorage.getItem('auth'))
}
const getters = {
  isLoggedIn: state => {
    return state.isLoggedIn
  },
  authentification: state => {
    return state.auth
  }
}
const mutations = {
  [types.LOGIN] (state) {
    state.pending = true
  },
  [types.LOGIN_SUCCESS] (state) {
    state.isLoggedIn = true
    state.pending = false
  },
  [types.LOGOUT] (state) {
    state.isLoggedIn = false
  }
}
const actions = {
  login ({
      state,
      commit,
      rootState
    }, creds) {
    console.log('login...', creds)
    commit(types.LOGIN) // show spinner
    return new Promise(resolve => {
      setTimeout(() => {
        localStorage.setItem('auth', JSON.stringify(creds))
        commit(types.LOGIN_SUCCESS)
        resolve()
      }, 1000)
    })
  },
  logout ({ commit }) {
    localStorage.removeItem('auth')
    commit(types.LOGOUT)
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}

我认为这会创建循环并在初始化存储之前调用http-common。

修改:根据要求添加验证模块:

selcet * from (
  select a.*, row_number() over (partition by facility_id_n
      order by usage_counter_n desc) rn
  from your_tbl a) 
where rn =1;

2 个答案:

答案 0 :(得分:1)

这实际上是Vue核心团队的ThorstenLünborg(LinusBorg)向我展示的更好的解决方案:

https://codesandbox.io/s/vn8llq9437

在您定义Axios实例并设置配置等​​的文件中,您还有一个Vuex插件,可以监视您的商店并根据商店中存在的任何身份验证令牌设置/删除您的授权标头。

答案 1 :(得分:0)

我找到了溶剂。我必须在调用之前分配auth,而不是在axios对象的反馈期间分配:

var axiosInstance = axios.create({
  baseURL: 'http://localhost:8081/'
})

axiosInstance.interceptors.request.use(
  config => {
    config.auth = store.getters['authentification']
    return config
  }, error => Promise.reject(error))

export default axiosInstance