我创建了登录页面。路由器拦截请求并验证用户是否经过身份验证。商店是维护用户是否登录。
调试时我正在使用auth.js
“商店未定义”
我还在导入中尝试了相对路径而不是@。
路由器代码段
import auth from '@/services/auth';
...
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!auth.loggedIn()) {
next({
path: '/login',
});
} else {
next();
}
} else {
next();
}
});
auth.js就像服务,它将与商店和维护状态进行交互。
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
import store from '@/store/UserStore';
Vue.use(VueAxios, axios);
export default {
login(credentials) {
return new Promise((resolve, reject) => {
Vue.axios.post('/api/authenticate', credentials).then((response) => {
localStorage.setItem('token', response.body.token);
store.commit('LOGIN_USER');
resolve();
}).catch((error) => {
store.commit('LOGOUT_USER');
reject(error);
});
});
},
isUserLoggedIn() {
return store.isUserLoggedIn();
},
};
这是我的商店
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
state: {
isLogged: !localStorage.getItem('token'),
user: {},
},
actions: {
},
mutations: {
/* eslint-disable no-param-reassign */
LOGIN_USER(state) {
state.isLogged = true;
},
/* eslint-disable no-param-reassign */
LOGOUT_USER(state) {
state.isLogged = false;
},
},
getters: {
isUserLoggedIn: state => state.isLogged,
},
modules: {
},
});
答案 0 :(得分:1)
更改 UserStore 中的导出类型,如下所示:
线
export default new Vuex.Store({
替换为
export const store = new Vuex.Store({