美文网首页Vue.js前端开发vue
vue路由守卫 - 全局

vue路由守卫 - 全局

作者: 可怜的小黑兔 | 来源:发表于2019-08-14 12:08 被阅读62次

前言

vue中用路由守卫来做是否登陆判断,此处我以后台管理项目为例,如下图:


admin.jpg

主要方法:

router.beforeEach((to,from,next)=>{ })
  • to:进入到哪个路由去
  • from:从哪个路由离开
  • next:路由的控制参数,常用的有next(true)和next(false)

首先判断进入的是否是login页面?然后再判断是否已经登陆?
已经登陆了就进入你要跳转的页面,没登录就进入login页面

为了更加明显一点,我将页面命名的简单一些,ps:
  • Login.vue是登陆页面
  • Index.vue是全局页面(包含公共导航组件)
    A.vue是普通页面(此处我做为首页)
    B.vue是普通页面
  • 404.vue是走丢了的404页面

实现代码

//router.js
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router);

const children = [
  {
    path: 'a',
    name: 'a',
    component: () => import('./views/A.vue'),
    meta: {
      title: 'a页面',
      keepAlive: false // 无缓存
    }
  },
  {
    path: 'b',
    name: 'b',
    component: () => import('./views/B.vue'),
    meta: {
      title: 'b页面',
      keepAlive: true // 有缓存
    }
  },
  {
    path: '404',
    name: '404',
    component: () => import('./components/404.vue')
  }
];
const router =  new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    { path: '/', redirect: '/a' },
    { path: '*', redirect: '/404' },
    {
      path: '/login',
      name: 'login',
      component: () => import('./components/Login.vue')
    },
    {
      path: '/',
      component: () => import('./components/Index.vue'), //index是上图左边的公共菜单
      children  //此处是站内页面,页面在右侧container里展示
    }
  ]
});
router.beforeEach((to, from, next) => {
  const isLogin = sessionStorage.getItem('isLogin'); //获取本地存储的登陆信息
  if (to.name == 'login') { //判断是否进入的login页
    if (isLogin == "true") {  //判断是否登陆
      next({ name: 'a'});  //已登录,跳转首页(a页面)
    } else {
      next();  //没登录,继续进入login页
    }
  } else { //如果进入的非login页
    if (isLogin == "true") {   //同样判断是否登陆
      next();  //已登录,正常进入
    } else {
      next({ name: 'login'});  //没登录,跳转到login页
    }
  }
});
export default router;

相关文章

  • 华云

    一,vue路由守卫的生命周期1,全局的前置路由守卫 router.beforeEach()2, 全局解析守卫 ...

  • vue-router 常见导航守卫

    全局守卫vue-router全局有三个守卫 路由独享守卫如果你不想全局配置守卫的话,你可以为某些路由单独配置守卫 ...

  • react实现路由守卫

    与vue不同,vue直接使用beforeEach即可实现全局路由守卫等功能。react要实现路由守卫得自己配置。实...

  • Vue设置路由拦截

    路由守卫 在Vue中分为全局前置守卫 router.beforeEach ,和全局后置钩子 router.afte...

  • vue导航守卫

    根据作用域的不同,vue导航守卫分三种:全局导航守卫、组件内部导航守卫、路由独享守卫 全局导航守卫,在main.j...

  • vue-router路由拦截器

    Vue Router 是vue.js官方路由管理器 路由出口 声明式导航 编程式导航 全局前置守卫 全局后置钩子 ...

  • 关于vue路由守卫做登陆状态判断的问题

    关于vue路由守卫做登陆状态判断的问题 直接上代码 // 全局路由守卫 router.beforeEach((to...

  • vue的路由守卫

    路由守卫分3种:全局守卫路由独享守卫组件内的路由守卫 1.全局守卫:beforeEachbeforeResolve...

  • Vue路由守卫

    一、全局路由守卫 全局路由前置守卫 当用Vue开发的时候,如果项目涉及登录的话,一般都要做登录验证。用户必须先登录...

  • 2021-04-11

    vue-router 路由钩子函数(导航守卫) 路由钩子函数有三种: 全局钩子: beforeEach(全局前置守...

网友评论

    本文标题:vue路由守卫 - 全局

    本文链接:https://www.haomeiwen.com/subject/zafgjctx.html