我正在为我的应用程序使用 vuex、axios,并且我想在 axios 启动中使用 getter 来通过基本身份验证。这是我的 axios init (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
}
我认为这会创建循环并在初始化存储之前调用 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
}
最佳答案
这实际上是 Vue 核心团队的 Thorsten Lünborg (LinusBorg) 向我展示的一个更好的解决方案:
https://codesandbox.io/s/vn8llq9437
在您定义 Axios 实例并设置配置等的文件中,您还有一个 Vuex 插件,可以监视您的商店并根据商店中任何身份验证 token 的存在设置/删除您的授权 header 。
关于javascript - Vuex 存储未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47848987/