一、实现目标
1.引言
作为一个刚做入门Vue的一个新手,可能会存在这样的疑惑,我是不是可以直接输入URL进行访问,那登录就没有意义了啊。为了解决这个问题,就得使用登录拦截器来实现。关于登录拦截,前后端都可以做,这里我简单介绍一下Vue前端的登录拦截。
2.需求分析
当输入访问非登录界面时,进行拦截分析,若有存储账号即可访问,未存储又不是登录界面就进行拦截并跳转登录界面。
二、具体实现
1.准备工作
(1)router(重点beforeEach)和Vue的搭建
(2)LocalStorge的了解参考文章
2.关键代码
login组件在登录成功使用LocalStorage存储
this.$axios.post('/adminLogin',params
).then( (response)=>{ //注意使用箭头函数
// handle success
// this.responseResult=JSON.stringify(response);
// if(response.status)
if(response.status==200){
if(response.data==true){
console.log(response);
console.log(response.data);
localStorage.setItem("userName",this.username);
this.$notify({
title:'成功',
message:'登录成功',
type:'success'
})
// alert(response.data);
// this.check=response.data;
this.$router.push({path:'/home'});
}else {
alert("密码错误,请重新输入");
}
}else{
console.log('失败');
alert("连接服务器失败")
}
})
.catch(function (error) {
// handle error
console.log(error);
alert("连接服务器失败")
})
},
store的index.js文件加入meta:{requireAuth:{true}}
{
path: '/healthWarning',
name: 'healthWarning',
component:healthWarning,
meta:{requireAuth: true}
},
main.js中进行beforeEach的使用
router.beforeEach((to, from, next) => {
if(to.name !==" /" && localStorage.getItem("userName")==null){
alert("请先登录")
this.$router.push({path:'/'})
}else next();
})