【问题标题】:Vuex store is undefinedVuex 商店未定义
【发布时间】:2017-12-16 18:58:33
【问题描述】:

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

import axios from 'axios'
import store from '@/store'

export default axios.create({
  baseURL: 'http://localhost:8081/',
  auth: store.getters['authentification']
})

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

我的商店有几个模块和那些模块。存储 index.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
  }
})

并且模块使用 axios init 函数来调用 REST api 即:

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

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

编辑:按要求添加认证模块:

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
}

【问题讨论】:

  • 认证模块在哪里?乍一看似乎不对,但我看不到所有代码。
  • @jostrander 我添加了身份验证模块。但这不是问题。正如我所写的,问题是导入链。我正在导入商店,但尚未初始化。 Auth 模块本身工作正常,但如果我想在 common-http 中使用它,它还没有定义

标签: javascript vue.js vuex


【解决方案1】:

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

https://codesandbox.io/s/vn8llq9437

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

【讨论】:

  • 最好展示一下解决方案如何工作的代码。
  • 那里有一个链接。你看不见吗?
【解决方案2】:

我找到了解决方案。我必须在调用之前而不是在 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

【讨论】:

    猜你喜欢
    • 2020-01-21
    • 2011-09-13
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多