The Vue project keeps the user logged in (the state remains after localStorage + vuex refreshes the page)

        In front-end project development, there is often a problem when implementing the user's login and registration function, that is, the login state we set disappears after the browser page is refreshed. This is actually just because we did not save the user state.

Here the pony demo uses the localStorage  + vuex method (other usages such as sessionStorage, cookies, etc. are the same, but the functions are different).  


1. Realize the effect

Implemented function: After the user logs in successfully, after refreshing the browser page or closing the browser and opening the page again, the login status remains until the user clicks to log out.

2. Implementation steps and key points involved

1. First, add an empty object userInfo{ } to the state attribute in vuex to save the state of the user after logging in;

Key points involved:

  • The state attribute (state) is used to add variables shared by multiple components, similar to data in vue;

2. On the login page, after judging that the login is successful, create an object userInfo{ }, add various attributes that describe the login status, and then store the objects in localStorage and vuex respectively; 

Key points involved:

  • The localStorage property allows access to the Storage object of the Document source, the stored data is kept in the browser session;
  • The only difference from sessionStorage is that localStorage belongs to permanent storage unless we manually clear it, while sessionStorage belongs to temporary storage, which will be emptied after the browser is closed.
    • : : LocalStorage.setItem ('myCat', 'Tom');
    • 取:var cat = localStorage.getItem("myCat");
    • 删:localStorage.removeItem("myCat"); 或 localStorage.clear("myCat");
  • JSON.stringify() serializes objects and converts the returned object type to a string type;
  • this.$store.state, take the properties in state in vuex, such as:
    • this.$store.state.userInfo = userInfo //Take out userInfo in vuex and assign it to new userInfo

3. In the mount stage, determine the login status userInfo; after setting the relevant properties, the login status can be saved normally.

Because localStorage is permanently saved, the login status still exists even if the browser is closed and the webpage is opened again, unless the localStorage data is manually cleared;

4. Set logout and clear data in localStorage;

5. Implement the function.

Third, the code involved

vuex(store/index.js)

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo:{}
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

Set the login page (part of the code, cannot be copied and used, just for reference)

login method

//登录方法
login() {
  //验证码的验证
  var randStr = this.rand.toString().replace(/,/g, ""); //随机生成的验证码为数组形式,此处将其转为字符串并去掉中间相隔的逗号
  var codeStr = this.code; //用户输入的验证码
  if (randStr.toLowerCase() == codeStr.toLowerCase()) { //比较用户输入的与随机生成的验证码,不区分大小写
    //获取登录接口
    axios.post("user/login", {
      name: this.name,
      password: this.password,
      administrator: this.usertyp
    }).then(result => {
      console.log(result.data);
      const code = result.data.code;
      this.token = code;
      if (this.token == 1003) {
        this.$message.error('用户名或密码未输入!');
      } else if (this.token == 1001) {
        this.$message.error('登录失败,请检查用户名或者密码是否正确。');
      } else if (this.token == 1005) {
        this.$message.error('您不是管理员,无管理员登录权限!');
      } else if (this.token == 200) {
        if (this.usertyp == "2") { //管理员登录
          this.$message.success('登录成功!');
          this.dialogFormVisible = false; //登录成功后登录插槽关闭
          this.loginReg = false;//隐藏登录注册按钮,显示欢迎信息
          this.manage = true;//显示管理员登录信息
          let userInfo = {
            isLogin: true,
            manage: true,
            name: this.name
          };
          localStorage.setItem("userInfo", JSON.stringify(userInfo));
          this.$store.state.userInfo = userInfo
          console.log('this.$store.state.userInfo', this.$store.state.userInfo)
          setTimeout(() => { //此处必须使用vue函数,否则this无法访vue实例
            this.$message(`欢迎您,管理员 ${this.name}!`)
          }, 2000);
          console.log(this.usertyp)
        } else if (this.usertyp == "") {  //普通用户
          this.$message.success('登录成功!');
          this.dialogFormVisible = false; //登录成功后插槽关闭
          this.loginReg = false;//隐藏登录注册按钮,显示欢迎信息
          this.user = true; //显示普通用户登录信息
          let userInfo = {
            isLogin: true,
            manage: false,
            name: this.name
          }
          localStorage.setItem("userInfo", JSON.stringify(userInfo));
          this.$store.state.userInfo = userInfo
          setTimeout(() => { //此处必须使用vue函数,否则this无法访vue实例
            this.$message(`欢迎您,尊贵的晋之魂用户 ${this.name}!`)
          }, 2000);
          console.log(this.usertyp)
        }
        this.Cookie.set("UserName", this.name); //将用户名存到cookie
        console.log('登录状态为:' + this.token);
      }
    })
  } else {
    this.$message.error('请输入正确的验证码');
  }
},

logout method

//退出登录
logout() {
  this.Cookie.remove("UserName");
  this.loginReg = true;
  this.manage = false;
  this.user = false;
  this.log_out = false;
  localStorage.clear();
  setTimeout(() => {
    this.$router.push({
      path: '/'
    }, () => {
    }, () => {
    });//退出登录后2秒后跳转至首页
  }, 2000)
  //加()=>{},()=>{} 可解决路由重复后台报错问题
},

Judging the login status in the mount phase

mounted() {
      // 判断登录状态
      let userInfo = JSON.parse(localStorage.getItem('userInfo'));
      if (null === userInfo) return;
      console.log('userInfo', userInfo.isLogin);
      if (userInfo.isLogin) {
        this.dialogFormVisible = false; //登录成功后插槽关闭
        this.loginReg = false;//隐藏登录注册按钮,显示欢迎信息
        this.name = userInfo.name;
        if (userInfo.manage) {
          this.manage = true;//显示管理员登录信息
        } else {
          this.user = true;//显示普通用户登录信息
        }
      }
    }

Tip: The pony uses vue + Element UI, and the code may be different when using other technologies, but the idea is the same.

Guess you like

Origin blog.csdn.net/weixin_53072519/article/details/124376758