Vue项目 用户登录状态持久存储 (即使刷新)

本地存储 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)
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值