【发布时间】:2018-08-23 14:52:30
【问题描述】:
我是 Vue 的新手(我是一个反应型的人),我遇到了这个问题。
axios.js
import store from '../../store/index';
import axios from 'axios'
const API_URL = process.env.API_URL;
const token = store.getters.auth.token;
export default axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
})
存储/index.js
import auth from './modules/auth'
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
state: {},
getters : {},
mutations: {},
actions:{},
modules: {
auth
},
strict: debug,
})
模块/授权
import { AUTH_SUCCESS, AUTH_GUEST } from '../actions/auth'
import axios from '../../util/axios/axios'
import Vue from "vue";
const state = {
token: localStorage.token || '',
};
const getters = {
token: state => state.token
};
const actions = {
[AUTH_GUEST]: async ({commit}) => {
await axios.post('auth/register',)
.then(response => {
commit(AUTH_SUCCESS, response);
})
.catch(error => {
console.log(error);
});
},
};
const mutations = {
[AUTH_SUCCESS]: (state, resp) => {
state.token = resp.data.token;
},
}
export default {
state,
getters,
actions,
mutations,
}
当尝试从store/index 获取商店时,它返回undefined。
可能在 store 初始化之前已经调用了 axios。
但是我该如何处理呢?
应用程序的流程是。
user register->get token->update store with this token->add to the axios header.
所以现在,所有对 api 的调用都将提供令牌。
【问题讨论】:
-
我怀疑问题出在 auth 模块上。当发出 axios 请求时,store 将已经初始化。您是否在 store 对象或 store.getters.auth.token 上未定义?
-
@AllkinI 在 store.getters.auth.token 上未定义
-
@Allkin 使用 auth 模块编辑了我的问题