有了这段代码,再也不用担心每进入一个页面发送一次checkLogin请求验证了
过多的名词等下次再来解释
看下面两部分:
1、路由文件
// 登陆页面不需要检测状态,所以不需要守卫
// login
{
path: '/login',
name: 'login',
component: Login,
meta: {
title: '登录'
}
},
// home页面需要进行登陆状态验证,所以增加路由元信息,mate里面设置要不要守卫
// home
{
path: '/',
name: 'home',
component: Home,
meta: {
requireLogin: true,
title: '欢迎回来'
}
}
2、hook文件
router.beforeEach(async (to, from, next) => {
Vue.prototype.$admin = Vue.prototype.$admin || {}
// check
// 检验不需要登陆状态的路由
if (!to.meta.requireLogin) {
//检验不需要登陆状态路由是否含有状态储存
if (!Vue.prototype.$admin.status) {
// 如果没有状态,进行请求
let res = await Vue.prototype.$api.get('/api')
Vue.prototype.$admin = res.data || {}
}
next()
} else {
// 检验需要登陆状态的路由
// 检验需要登陆状态路由是否含有状态储存
if (Vue.prototype.$admin.status) {
// 有就继续
next()
} else {
// 没有就请求
let res = await Vue.prototype.$api.get('/api')
if (res.data.status == '已登陆') {
Vue.prototype.$admin = res.data
next()
} else {
// 请求状态未登录就返回登陆页面
next('/login')
}
}
}
})
然后就达到了:不管跳转多少页面,就只发送一次checkLogin的请求的效果