1、登陆
编写登陆表单,给“提交”按钮绑定一个点击事件"loginCheck",当点击提交的时候,把用户名和密码发送到后端登陆接口,后端会对用户名和密码进行校验,校验通过后,返回token。
前端接收到token,把token进行本地存储,把用户名存入vuex,然后进入系统首页。
async loginCheck(){
const res=await axios.post('http://localhost:8000/login',{
username:this.username,
password:this.password
});
// 把用户名和密码发送到登陆接口,后端验证通过后返回token,把token和用户名存储到本地,
if(res.status===200){
localStorage.setItem('token',res.data.token);
this.$store.commit('setUsername',this.username);
this.$router.push('/');
}else{
this.$router.push(('/login'));
}
console.log(res);
}
2、退出
点击退出时,清除token和vuex存储的用户信息
loginOut(){
console.log('login-out');
localStorage.removeItem('token');
this.$store.commit('removeUsername');
this.$router.push('/login');
}
3、路由守卫
有一些界面是需要登陆才能访问的,对于这些界面需要配置路由守卫
思路:第一步:通过路由元信息meta标识需要登陆才能访问的界面 。第二步:配置全局守卫。
routes:[
{
path:'/',
component:Main,
redirect:'/home',
meta:{isLogin:true}, //meta进行标识
children:[
{path:'home',component:Home},
{path:'user',component:User},
{path:'mall',component:Mall},
{path:'page1',component:PageOne},
{path:'page2',component:PageTwo}
]
},
{path:'/login',component:Login}
]
这里,除了'/login'是可以不需要登陆就能访问的 ,其他 '/'、'/home'、'/user'、'/mall'、'page1'、
'page2'、都是需要登陆才能访问的。你可以在每一个中配置用于标识的meta,也可以只在根路由'/'上配置,然后通过遍历matched,判断是否存在meta中isLogin为true,存在这说明这是需要登陆才能进入的界面。
router.beforeEach((to,from,next)=>{
// 判断是否是需要登陆才能进入的界面
if(to.matched.some(item=>item.meta.isLogin)){
// 是否是登陆状态
if(localStorage.getItem('token')){
next();
}else{
next('/login')
}
}else{
next()
}
})
matched方法:
routes:[{
path:'/',component:Main,
children:[
{path:'home',component:Home,
children:[{path:'a',component:PageOne}]
}]
}]
/home/a路由的matched是下面这个结果: