[Vue]路由守卫

简介: [Vue]路由守卫

前言

系列文章目录:

[Vue]目录

老师的课件笔记,不含视频 https://www.aliyundrive.com/s/B8sDe5u56BU

笔记在线版: https://note.youdao.com/s/5vP46EPC

视频:尚硅谷Vue2.0+Vue3.0全套教程丨vuejs从入门到精通

1. 路由守卫

1.1 概念

路由守卫能够对路由进行权限控制,即在路由进行改变时,可以判断当前能否访问路由对应的组件。

1.2 分类

路由守卫分为:全局守卫、独享守卫、组件内守卫。

2. 全局路由守卫

2.1 全局前置路由守卫

全局前置路由守卫会在初始化时被触发,在每次进行路由的切换前也会被触发。

// 全局前置路由守卫
// 在初始化时被触发,在每次进行路由的切换前也会被触发
// 全局前置路由守卫的回调函数接收三个参数
// to:表示将要访问的路由的信息对象
// from:表示将要离开的路由的信息对象
// next:是一个函数,表示放行的意思,调用next()才可以访问to的路由
router.beforeEach((to, from, next) => {
})
router.beforeEach((to, from, next) => {
  console.log(to, from)
})

实现如果localStorage中存在school的值为SGG则可以对News组件和Message组件进行访问,如果school的值不为SGG则不能进行访问。其他组件可以不用判断直接放行。

router/index.js

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import Message from '../pages/Message'
import News from '../pages/News'
import Detail from '../pages/Detail'
// 创建一个路由器
// 路由器的暴露需要在路由守卫之后,
// 否则路由守卫不会触发(路由守卫控制权限之前路由器已经被暴露出去了)
const router = new VueRouter({
  routes: [
    {
      name: 'about',
      path: '/about',
      component: About
    },
    {
      name: 'home',
      path: '/home',
      component: Home,
      children: [
        {
          name: 'news',
          path: 'news',
          component: News
        },
        {
          name: 'message',
          path: 'message',
          component: Message,
          children: [
            {
              name: 'messageDetail',
              path: 'detail',
              component: Detail,
              props($route) {
                return {
                  id: $route.query.id,
                  title: $route.query.title
                }
              },
            }
          ]
        }
      ]
    }
  ]
})
// 全局前置路由守卫
// 在初始化时被触发,在每次进行路由的切换前也会被触发
// 全局前置路由守卫的回调函数接收三个参数
// to:表示将要访问的路由的信息对象
// from:表示将要离开的路由的信息对象
// next:是一个函数,表示放行的意思,调用next()才可以访问to的路由
router.beforeEach((to, from, next) => {
  console.log(to)
  // 通过路由的name判断要前往的路由
  // 如果要访问 News Message 组件进行权限判断
  if (to.name === 'news' || to.name === 'message') {
    // 判断 school 的值是否为 SGG
    if (localStorage.getItem('school') === 'SGG') {
      next()
    } else {
      alert('school的值不为SGG,不能访问')
    }
  } else { // 访问其他组件直接放行
    next()
  }
})
// 保留路由器
export default router

2.2 meta

在配置路由时,可以传入meta配置项,在meta配置项中可以写我们自己的数据,可以用于判断当前路由是否需要进行权限的判断。

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  console.log(to)
  // 路由meta中的isAuth为true则要进行权限的控制
  if (to.meta.isAuth) {
    // 判断 school 的值是否为 SGG
    if (localStorage.getItem('school') === 'SGG') {
      next()
    } else {
      alert('school的值不为SGG,不能访问')
    }
  } else { // 访问其他组件直接放行
    next()
  }
})
// 创建一个路由器
const router = new VueRouter({
  routes: [
    {
      name: 'about',
      path: '/about',
      component: About,
      meta: {isAuth: false}
    },
    {
      name: 'home',
      path: '/home',
      component: Home,
      children: [
        {
          name: 'news',
          path: 'news',
          component: News,
          meta: {isAuth: true}
        },
        {
          name: 'message',
          path: 'message',
          component: Message,
          meta: {isAuth: true},
          children: [
            {
              name: 'messageDetail',
              path: 'detail',
              component: Detail,
              props($route) {
                return {
                  id: $route.query.id,
                  title: $route.query.title
                }
              },
            }
          ]
        }
      ]
    }
  ]
})

2.3 全局后置路由守卫

全局后置路由守卫会在初始化时被触发,在每次进行路由的切换后也会被触发。

// 全局后置路由守卫
// 在初始化时被触发,在每次进行路由的切换后也会被触发
// 全局前置路由守卫的回调函数接收两个参数
// to:表示将要访问的路由的信息对象
// from:表示将要离开的路由的信息对象
// 全局后置路由守卫无 next
router.afterEach((to, from, next) => {
  console.log(to, from, next)
})

访问相关组件之后,实现页面标题根据当前不同组件进行切换。

// 创建一个路由器
const router = new VueRouter({
  routes: [
    {
      name: 'about',
      path: '/about',
      component: About,
      meta: {isAuth: false, title: '关于'}
    },
    {
      name: 'home',
      path: '/home',
      component: Home,
      meta: {isAuth: false, title: '主页'},
      children: [
        {
          name: 'news',
          path: 'news',
          component: News,
          meta: {isAuth: true, title: '新闻'}
        },
        {
          name: 'message',
          path: 'message',
          component: Message,
          meta: {isAuth: true, title: '消息'},
          children: [
            {
              name: 'messageDetail',
              path: 'detail',
              component: Detail,
              meta: {isAuth: false, title: '详情'},
              props($route) {
                return {
                  id: $route.query.id,
                  title: $route.query.title
                }
              },
            }
          ]
        }
      ]
    }
  ]
})
// 全局后置路由守卫
router.afterEach((to, from, next) => {
  // console.log(to, from, next)
  // 切换页面的标题
  document.title = to.meta.title
})

3. 独享路由守卫

独享路由守卫写在每个路由对应的配置中,即独享路由守卫是每个路由所独享的,独享路由守卫与全局前置路由守卫类似。

注意:独享路由守卫与全局路由守卫不一样,独享路由守卫不分前置和后置。

注释全局前置路由守卫

// 创建一个路由器
const router = new VueRouter({
  routes: [
    ......
    {
      name: 'home',
      path: '/home',
      component: Home,
      meta: { isAuth: false, title: '主页' },
      children: [
        {
          name: 'news',
          path: 'news',
          component: News,
          meta: { isAuth: true, title: '新闻' },
          beforeEnter(to, from, next) {
            console.log(to, from)
            // 判断 school 的值是否为 SGG
            if (localStorage.getItem('school') === 'SGG') {
              next()
            } else {
              console.log('school的值不正确,不能访问')
              alert('school的值不正确,不能访问')
            }
          }
        },
        ......
          ]
        }
      ]
    }
  ]
})

4. 组件内路由守卫

组件内路由守卫写在组件内,组件路由守卫有:

1.beforeRouteEnter:通过路由规则,进入该组件时被调用

2.beforeRouteLeave:通过路由规则,离开该组件时被调用

注释全局前置路由守卫与全局后置路由守卫

<template>
  <div>
    <h2>About组件</h2>
  </div>
</template>
<script>
export default {
  name: 'About',
  beforeRouteEnter(to, from, next) {
    console.log('beforeRouteEnter')
    console.log(to)
    console.log(from)
    next()
  },
  beforeRouteLeave(to, from, next) {
    console.log('beforeRouteLeave')
    console.log(to)
    console.log(from)
    next()
  }
}
</script>
<style>
</style>

5. 总结 路由守卫

  1. 作用:对路由进行权限控制
  2. 分类:全局守卫、独享守卫、组件内守卫
  3. 全局守卫:
//全局前置守卫:初始化时执行、每次路由切换前执行
router.beforeEach((to,from,next)=>{
  console.log('beforeEach',to,from)
  if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
    if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则
      next() //放行
    }else{
      alert('暂无权限查看')
      // next({name:'guanyu'})
    }
  }else{
    next() //放行
  }
})
//全局后置守卫:初始化时执行、每次路由切换后执行
router.afterEach((to,from)=>{
  console.log('afterEach',to,from)
  if(to.meta.title){ 
    document.title = to.meta.title //修改网页的title
  }else{
    document.title = 'vue_test'
  }
})
  1. 独享守卫:
beforeEnter(to,from,next){
  console.log('beforeEnter',to,from)
  if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
    if(localStorage.getItem('school') === 'atguigu'){
      next()
    }else{
      alert('暂无权限查看')
      // next({name:'guanyu'})
    }
  }else{
    next()
  }
}
  1. 组件内守卫:
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter (to, from, next) {
},
//离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeave (to, from, next) {
}


相关文章
|
6天前
|
移动开发 JavaScript API
Vue Router 核心原理
Vue Router 是 Vue.js 的官方路由管理器,用于实现单页面应用(SPA)的路由功能。其核心原理包括路由配置、监听浏览器事件和组件渲染等。通过定义路径与组件的映射关系,Vue Router 将用户访问的路径与对应的组件关联,支持哈希和历史模式监听 URL 变化,确保页面导航时正确渲染组件。
|
10天前
|
监控 JavaScript 前端开发
ry-vue-flowable-xg:震撼来袭!这款基于 Vue 和 Flowable 的企业级工程项目管理项目,你绝不能错过
基于 Vue 和 Flowable 的企业级工程项目管理平台,免费开源且高度定制化。它覆盖投标管理、进度控制、财务核算等全流程需求,提供流程设计、部署、监控和任务管理等功能,适用于企业办公、生产制造、金融服务等多个场景,助力企业提升效率与竞争力。
61 12
|
6天前
|
JavaScript 前端开发 开发者
Vue中的class和style绑定
在 Vue 中,class 和 style 绑定是基于数据驱动视图的强大功能。通过 class 绑定,可以动态更新元素的 class 属性,支持对象和数组语法,适用于普通元素和组件。style 绑定则允许以对象或数组形式动态设置内联样式,Vue 会根据数据变化自动更新 DOM。
|
7天前
|
JavaScript 前端开发 数据安全/隐私保护
Vue Router 简介
Vue Router 是 Vue.js 官方的路由管理库,用于构建单页面应用(SPA)。它将不同页面映射到对应组件,支持嵌套路由、路由参数和导航守卫等功能,简化复杂前端应用的开发。主要特性包括路由映射、嵌套路由、路由参数、导航守卫和路由懒加载,提升性能和开发效率。安装命令:`npm install vue-router`。
|
28天前
|
JavaScript 安全 API
iframe嵌入页面实现免登录思路(以vue为例)
通过上述步骤,可以在Vue.js项目中通过 `iframe`实现不同应用间的免登录功能。利用Token传递和消息传递机制,可以确保安全、高效地在主应用和子应用间共享登录状态。这种方法在实际项目中具有广泛的应用前景,能够显著提升用户体验。
54 8
|
JavaScript Go
|
JavaScript C语言 Go
|
2月前
|
JavaScript
vue使用iconfont图标
vue使用iconfont图标
147 1
|
28天前
|
存储 设计模式 JavaScript
Vue 组件化开发:构建高质量应用的核心
本文深入探讨了 Vue.js 组件化开发的核心概念与最佳实践。
74 1
|
3月前
|
JavaScript 前端开发 开发者
vue 数据驱动视图
总之,Vue 数据驱动视图是一种先进的理念和技术,它为前端开发带来了巨大的便利和优势。通过理解和应用这一特性,开发者能够构建出更加动态、高效、用户体验良好的前端应用。在不断发展的前端领域中,数据驱动视图将继续发挥重要作用,推动着应用界面的不断创新和进化。
111 58

热门文章

最新文章