本地存储 isLogin 登录状态 并保存到vuex
Header.vue
<div class="content-login-success" v-if="isLogin">
<div style="cursor: pointer">我的课程</div>
<div @mouseenter="isUserInfo = true">
<!-- 用户头像 -->
<img
class="avator"
:src="userInfo.avatar"
alt=""
v-if="userInfo.avatar"
/>
<!-- 默认头像 -->
<img class="avator" :src="avatarImg" alt="" v-else />
<!-- 头像信息 -->
</div>
</div>
import api from "../../common/api/auth";
import { mapState, mapMutations, mapActions } from "vuex";
computed: {
//
...mapState({
userInfo: (state) => state.user.userInfo,
isLogin: (state) => state.user.isLogin,
}),
},
methods: {
...mapActions(["saveUserInfoAction", "saveLoginStatusAction"]),
//账号密码登录 按钮
submitPhoneForm(phoneFormRef) {
this.$refs[phoneFormRef].validate((valid) => {
if (!valid) return; //验证通过否
if (valid) {
//开启加载动画
var phoneLoading = Loading.service({
lock: true,
text: "loading",
spinner: "el-icon-loading",
background: "rgba(0,0,0,0.7)",
});
}
let username = Encrypt(this.phoneForm.username);
let password = Encrypt(this.phoneForm.password);
api
.loginByJson({
username,
password,
})
.then((res) => {
//console.log(res);
if (res.meta.code === "10006") {
//10006为登录成功
let accessToken = res.data.accessToken;
//本地存储
localStorage.setItem("token", Encrypt(accessToken));
localStorage.setItem("isLogin", JSON.stringify(true));
//改变vuex中登录状态
this.saveLoginStatusAction();
console.log(this.isLogin);
//调用获取用户信息的方法
this.getUserInfo();
this.$message({
message: "登录成功,请去学习!",
type: "success",
});
this.$router.go(0); //刷新当前页面
} else {
this.$message({
message: res.meta.msg,
type: "error",
});
}
//关闭加载动画
phoneLoading.close();
this.loginDialog = false;
})
.catch((err) => {
phoneLoading.close();
this.$message({
message: res.meta.msg,
type: "error",
});
});
});
},
//退出登录
goLogout() {
this.$confirm("您确认要退出登录吗", "提示信息", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(() => {
api
.logOut()
.then((res) => {
this.$message({
type: "success",
message: "退出成功",
});
localStorage.removeItem("token");
localStorage.removeItem("isLogin");
this.saveLoginStatusAction(false);
this.$router.push("/");
})
.catch((err) => {
console.log(err);
});
})
.catch(() => {
this.$message({
type: "info",
message: "已经取消退出",
});
return;
});
}
},
modules/user.js
export default {
state: {
userInfo: {
avatar: '/image/common/avator.png',
nickName: '默认昵称',
gender: 1,
city: '成都',
id: 1
},
isLogin: JSON.parse(localStorage.getItem('isLogin')) || false//默认的登录状态
},
getters: {
},
mutations: {
saveUserInfo(state, payLoad) {
state.userInfo = payLoad
},
saveLoginStatus(state, payload) {
state.isLogin = payload
}
},
actions: {
saveUserInfoAction({ commit }, payLoad) {
commit('saveUserInfo', payLoad)
},
saveLoginStatusAction({ commit }, payLoad) {
commit('saveLoginStatus', payLoad)
}
}
}
|