Vue路由守卫笔记

路由守卫

当路由切换时,判断权限

路由守卫类型

1.全局守卫
2.独享守卫
3.组件内守卫

1.全局守卫

1.前置路由守卫 全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
在需要加上路由守卫的路由配置中加上
meta:{isAuth:true}

 {
   
        path: '/',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        meta: {
    isAuth: true, title:'主页' },
    },
//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
   
    //如果路由需要验证
    if (to.meta.isAuth) {
   
        if (localStorage.getItem('123') === '123') {
   
            next()  //放行
        } else {
   
            alert('抱歉,您无权限查看!')
        }
    } else {
   
        // 否则,放行
        next()
    }
})

2.后置路由守卫 ,路由跳转之后执行的事件,一般用作跳转路由后更改网页名

{
   
        path: '/',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        meta: {
    isAuth: true, title:'主页' },
    },
//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
   
    document.title = to.meta.title || '默认名'    //修改网页的title
})

3.独享路由守卫,某一个路由所单独享用的路由守卫,独享路由守卫只有前置没有后置

    {
   
        path: '/',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        meta: {
    isAuth: true },
        beforeEnter: (to, from, next) => {
   
            if (to.meta.isAuth) {
    //判断是否需要授权
                if (localStorage.getItem('123') === '123') {
   
                    next()  //放行
                } else {
   
                    alert('抱歉,您无权限查看!')
                }
            } else {
   
                next()  //放行
            }
        }
    },

4.组件内守卫

//通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next) {
   
  if(toString.meta.isAuth){
   
    if(localStorage.getTime('123')==='123'){
   
      next()
    }else{
   
      alert('无权限查看!')
    }
  } else{
   
    next()
  }
},
 
//通过路由规则,离开该组件时被调用 
beforeRouteLeave(to,from,next) {
   
 next()
}

相关推荐

  1. Vue守卫笔记

    2023-12-11 23:54:01       37 阅读
  2. vue - 守卫

    2023-12-11 23:54:01       14 阅读
  3. vue-router(守卫)

    2023-12-11 23:54:01       12 阅读
  4. Vue router(守卫)

    2023-12-11 23:54:01       11 阅读
  5. vue2 守卫讲解。

    2023-12-11 23:54:01       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-11 23:54:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-11 23:54:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-11 23:54:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-11 23:54:01       20 阅读

热门阅读

  1. Git命令---查看远程仓库

    2023-12-11 23:54:01       37 阅读
  2. Golang AI框架:探索人工智能与Go语言的结合

    2023-12-11 23:54:01       42 阅读
  3. 使用IDA调试工具辅助排查C++软件异常问题

    2023-12-11 23:54:01       39 阅读
  4. SAP UI5 walkthrough step8 Translatable Texts

    2023-12-11 23:54:01       32 阅读
  5. C盘瘦身,C盘清理

    2023-12-11 23:54:01       35 阅读
  6. 小功能实现(二十)分类统计,Map取值自增

    2023-12-11 23:54:01       30 阅读
  7. 704. 二分查找

    2023-12-11 23:54:01       35 阅读