Vue 全局路由守卫(Day55)

81 阅读1分钟

路由守卫

路由文件基础配置

import VueRouter from "vue-router";
import About from '@/pages/About.vue'
import Home from "@/pages/Home.vue";
import Message from "@/pages/Message.vue";
import News from "@/pages/News.vue";
import Detail from "@/pages/Detail.vue";
const router= new VueRouter({
    routes: [
        {
            name: 'ABout',
            path: '/about',
            component: About,
            meta:{title:'关于'}
        },
        {
            path: '/home',
            name:'HOme',
            component: Home,
            meta:{title:'主页'},
            children: [
                {
                    path: 'message',
                    name:'MEssage',
                    component: Message,
                    meta:{isAuth:true,title:'消息'},
                    children: [
                        {
                            name: 'DEtail',
                            path: 'detail',
                            component: Detail,
                            meta:{isAuth:true,title:'详情'},
                            props($route){
                                return {
                                    id:$route.query.id,
                                    title:$route.query.title
                                }
                            }
                        }
                    ]
                },
                {
                    name: 'NEws',
                    path: 'news',
                    component: News,
                    meta:{isAuth:true,title:'新闻'}
                }
            ]
        },
    ]
})
export default router

作用: 通过跳转或取消的方式守卫导航,对路由进行权限控制

分类: 全局守卫、独享守卫、组件内守卫

全局守卫

前置守卫

  1. 作用时机: 初始化、每次路由切换前执行

  2. 实现:

    1. 初始鉴权方式

      router.beforeEach((to, from, next)=>{
          if (to.name==='NEws' || to.name==='MEssage'){
              if (localStorage.getItem('name')==='test'){
                  next()
              }
          }else {
              next()
          }
      })
      
    2. 使用路由元信息进行鉴权

      router.beforeEach((to, from, next)=>{
          // 是否需要鉴权
          if (to.meta.isAuth){
              if (localStorage.getItem('name')==='test'){
                  next()
              }
          }else {
              next()
          }
      })
      

后置守卫

  1. 作用时机: 初始化、每次路由切换后执行

  2. 实现

    router.afterEach((to,from)=>{
        document.title=to.meta.title|| '开始'
    })