在nuxt中使用vuex-persistedstate(场景是登录后存储用户的信息)
1.login.vue
async login(params) {
try {
const res = await login(Object.assign(params, this.getcodeinfo));
if (res.code == 200) {
this.$message.success("登录成功!");
this.form.resetFields();
this.SAVEUSERINFO(res.data);//保存用户信息
this.$router.push("/");
} else {
this.$message.error(res.info);
}
} catch (error) {
console.error(error);
}
},
2.mutation.js
export default {
SAVEUSERINFO(state, info){
state.user = info
},
REMOVEUSERINFO(state){
state.user = {}
}
}
3.default.vue
<a-menu-item class="header-right" v-if="getToken !== ''">
<a-tooltip overlayClassName="tooltip">
<template slot="title">
<section class="tooltip-cont">
<h2>{{getName}}</h2>
<p>个人中心</p>
<p @click="logout">退出</p>
</section>
</template>
<a-avatar icon="user" />
</a-tooltip>
</a-menu-item>
</a-menu>
computed: {
...mapGetters([
"getToken",
"getName"
])
},
methods:
...mapMutations(["REMOVEUSERINFO"]),
async logout() {
try {
const res = await logout({ token: this.getToken });
if (res.code == 200) {
this.$message.success("注销成功!");
this.REMOVEUSERINFO();//清除用户信息
this.$router.go(0);
} else {
this.$message.error(res.info);
}
} catch (error) {
console.error(error);
}
}
4.getters.js
export default {
getToken (state) {
return state.user && state.user.token
},
getName (state) {
return state.user && state.user.username
}
}
5.持久化处理
先安装 : npm i vuex-persistedstate --save
plugins文件下新建localStorage.js
import createPersistedState from "vuex-persistedstate"
export default ({store}) => {
createPersistedState({
})(store)
}
具体vuex-persistedstate操作请看:https://github.com/robinvdvleuten/vuex-persistedstate