after the login is successful, save the login information to localStorage. The login registration should be changed to the user name on the home page after login, and the drop-down selection should be included. In the component, I judge which part of the component is displayed according to v-if, and the result does not achieve the desired effect. I do not know where the problem lies
login:
Login(this.credentials.email,this.credentials.password)
.then(res => {
var data = res.data;
if(data.error == ""){
this.SET_USER(data.data);
this.$router.go(-1);
}
})
SET_USER and GET_USER:
[SET_USER](state, user) {
state.user = user;
setStore("user_id", user.id);
setStore("user_name", user.username);
setStore("session_id", user.session_id);
},
[GET_USER](state, user) {
state.user = user;
}
setStore and getStore:
/**
* localStorage
*/
export const setStore = (name, content) => {
if (!name) return;
if (typeof content !== "string") {
content = JSON.stringify(content);
}
window.localStorage.setItem(name, content);
}
/**
* localStorage
*/
export const getStore = name => {
if (!name) return;
return window.localStorage.getItem(name);
}
header component:
<template v-if="user">
<router-link to="/login" :exact="true"></router-link>
<router-link to="/signin" :exact="true"></router-link>
</template>
<template v-else>
<b-nav-item-dropdown :right="!isRTL" class="demo-navbar-user">
<template slot="button-content">
<span class="d-inline-flex flex-lg-row-reverse align-items-center align-middle">
<span class="px-1 mr-lg-2 ml-2 ml-lg-0">{{ user.username }}</span>
</span>
</template>
<b-dd-item><i class="ion ion-ios-person text-lightest"></i> </b-dd-item>
<b-dd-divider />
<b-dd-item><i class="ion ion-ios-log-out text-danger"></i> </b-dd-item>
</b-nav-item-dropdown>
</template>
<script>
import { mapState, mapActions } from "vuex"
import { GET_USER } from "@/store/mutations"
export default {
name: "app-layout-navbar",
props: {
sidenavToggle: {
type: Boolean,
default: true
}
},
created(){
this.getUser();
},
mounted(){
},
computed: mapState({
user: state => {
console.log(state,"mapstate");
return state.user
}
}),
methods: {
...mapActions([
"getUser"
]),
toggleSidenav () {
this.layoutHelpers.toggleCollapsed()
},
getLayoutNavbarBg () {
return this.layoutNavbarBg
}
},
}
</script>
action:
export default {
login(context, user) {
context.commit(SET_USER, user);
},
getUser(context, user) {
var data = {
id: getStore("user_id"),
username: getStore("user_name"),
session_id: getStore("session_id"),
}
context.commit(GET_USER, data)
}
}
store:
const state = {
user: null
};
Vue.use(Vuex)
const store = new Vuex.Store({
state,
mutations,
actions
})
vue-devtools:
The user in
Base State cannot get a value. I don"t know if it was triggered incorrectly or for some reason when I refreshed.