vue project, after refreshing, the data in store is lost. I use localstorage to store it. When I take it out, I find that the page will report an error. I don"t know why.
Code:
login:
methods: {
...mapMutations([
"SET_USER",
]),
Login(){
Login(this.credentials.email,this.credentials.password)
.then(res => {
console.log(res.data,"")
var data = res.data;
if(data.error == ""){
this.SET_USER(data.data);
console.log(data.data);
this.$router.go(-1);
}
})
}
}
actions:
login(context, user) {
context.commit(SET_USER, user);
},
getUser(context, user) {
var data = {
id: getStore("user_id"),//localStorage
username: getStore("user_name"),
session_id: getStore("session_id"),
}
context.commit(GET_USER, data)
}
mutations:
[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;
}
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:
mounted(){
this.getUser()
},
methods: {
...mapActions([
"getUser"
]),
toggleSidenav () {
this.layoutHelpers.toggleCollapsed()
},
getLayoutNavbarBg () {
return this.layoutNavbarBg
}
},
computed: {
...mapState([
"user"
])
},
getStore and setStore:
/**
* 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);
}
/**
* localStorage
*/
export const removeStore = name => {
if (!name) return;
window.localStorage.removeItem(name);
}
in this way, the page will throw an exception
vue-devtoolsstate