【发布时间】: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