1.定义路由的时候配置 属性,requireAuth用来标记跳转的这个路由是否需要检测登录

下面的两个页面,登录页不需要检测,首页需要检测

const routers = [
{
   path: \'/\',
   component: App,
   children: [
    { 
    path: \'/login\', 
    component: Login,
    : {
     : \'登录\'

   }
   },
   { 
    path: \'/home\', 
    component: Home,
    : {
     : \'首页\',
    requireAuth: true
   }
   }
  ]
}
]
export default routers

2.main.js

返回遍历的某个路由对象,我们定义为record,检测这个对象是否拥有 这个对象,如果有 这个对象,检测 对象是不是有requireAuth这个属性且为true

检测到需要登录权限后,我的做法是请求接口判断用户是否登录

如果未登录,跳转到登录页面;如果已经登录,确保要调用next()方法,否则钩子就不会被resolved

router.beforeEach((to, from, next) => {
 /* 页面  */
 if (to. . ) {
  document.  = to. . 
 }
 /* 判断该路由是否需要登录权限 */
 if (to.matched.some(record => record. .requireAuth)) {
  //是否登录
  axios.post(\'/home/user/isLogin\')
    .then(function (response) {
      if (response.data.code == 0) {
        //未登录
        if (response.data.data.online == 0) {
          next({
            path: \'/login\',
          })
        } else {
          //已登录
          next()
        }
      }
    })
    .catch(function (error) {
      // Toast(error.data.msg);
    });

 }
 next();
})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

收藏 打印