全局前置守卫验证登录状态
在login页
methods: {
login() {
this.$axios
.post("/api", {
user: this.user,
password: this.pass
})
.then(res => {
if (res.data == 1) {
this.$message({
message: "登录成功",
type: "success"
});
//数据发到后台验证成功后,后台返回1存入本地localStorage,
localStorage.setItem('token',res.data)//存入token,进行登录判断
// console.log()
this.$store.commit("initstoreLogin",{
user: this.user,
password: this.pass
})
this.$router.push("/");
} else {
this.$message({
showClose: true,
message: "用户名或密码错误",
type: "error"
});
}
});
}
}
在main.js下
/ 全局前置守卫
router.beforeEach((to,from,next)=>{
let token = localStorage.getItem("token")//验证登录状态
if(token){//判断是否登录
next()
}
else{
if(to.path!=='/login'){
alert("请先登录")
next({path:'/login'})
}
else{
next()
}
}
})