我目前正在使用Vue.js / Vuex和Laravel PHP进行Web应用程序的登录身份验证部分。
身份验证成功后,我想从后端调用我的userObject(属性包括:电子邮件,role_id等),并在前端(navbar组件)中显示特定的属性。
我已经检查了localStorage并将userObject存储在此处,但似乎未提交到我的商店(currentUser)(Vue开发人员工具显示currentUser {}为空)
以下是我的代码:
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import Api from './_services/Api.js';
Vue.use(Vuex)
export default new Vuex.Store({
state: {
currentUser: {},
},
mutations: {
SET_CURRENT_USER(state, user) {
state.currentUser = user;
window.localStorage.currentUser = JSON.stringify(user);
},
LOGOUT_USER(state) {
state.currentUser = {}
window.localStorage.currentUser = JSON.stringify({});
}
},
actions: {
logoutUser({commit}) {
commit('LOGOUT_USER')
},
async loginUser({commit}, loginInfo) { //store.js
console.log(loginInfo)
try {
let response = await Api().post('/login', loginInfo);
console.log(response)
let user = response.data.user;
console.log(user)
commit('SET_CURRENT_USER', user);
console.log(JSON.parse(window.localStorage.currentUser));
return user;
} catch {
return {error: "Email / Password combination was incorrect or unrecognized by the system. Please try again."}
}
}
}
})
navbar.vue
<template>
<nav>
<v-toolbar app :fixed="toolbar.fixed" :clipped-left="toolbar.clippedLeft" color="black">
<v-toolbar-side-icon class= "white--text" @click.stop="toggleMiniDrawer"></v-toolbar-side-icon>
<v-toolbar-title class="text-uppercase white--text" >
<v-btn flat to="/dashboard">
<h1 class="font-weight-black display-1 white--text" >Activities</h1>
</v-btn>
</v-toolbar-title>
<v-spacer></v-spacer>
<h1 class="font-weight-regular title white--text">{{currentUser.name + ', ' + currentUser.email}}</h1>
</v-toolbar>
<v-list-tile @click="logoutUser">
<v-list-tile-action>
<v-icon class="black--text">exit_to_app</v-icon>
</v-list-tile-action>
<v-list-tile-content >
<v-list-tile-title class="black--text">Logout</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
</v-flex>
</v-list>
</v-navigation-drawer>
</nav>
</template>
<script>
import axios from 'axios'
import { mapState } from 'vuex';
export default {
data(){
return{
}
},
methods: {
logoutUser () {
this.$store.dispatch("logoutUser");
}
},
computed: {
...mapState(['currentUser'])
}
};
</script>
我尝试将数据明确存储在store.js中的currentUser {}中
currentUser{name: 'Test', email: 'test@mail.com'}
,它成功显示在导航栏中。
这使我得出的结论是,我无法将userObject从“ user”成功地放置到“ currentUser {}”,或者说,它在重新加载后不会持续存在。
谢谢!