Vue项目如何保持用户登录状态(localStorage+vuex刷新页面后状态依然保持)
//登录方法
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('请输入正确的验证码');
}
},
- .NET Core系列之MemoryCache 初识
- 007手机一键Root(安机网一键Root) v3.0 官方最新版 一键ROOT您的Android手机
- 12306密码被盗了怎么办?12306密码外泄解决方法
- 12个字的qq网名
- 150M迷你型无线路由器怎么设置?
- 192.168.1.1打不开怎么办?路由器192.168.1.1打不开的原因以及解决办法
- 2011年电子报合订本 电子报 编辑部 中文 PDF版 [84M]
- 2015年1月15日小米新旗舰发布会现场图文直播
- 2016.3.1vivo Xplay5新品发布会现场视频直播 优酷直播
- 2016华为P9发布会视频直播地址 4月15日华为P9国行发布会直播