vue3 全局路由守卫

// 使用 TypeScript 时需要导入路由项目的类型声明
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/page/login/login.vue'

// 使用路由项目类型声明一个路由数组
const routes: Array<RouteRecordRaw> = [
    {
        path: '/',          
        component:Login,
    },
    {
        path: '/tourist',   
        name:'tourist',       
        component: () => import('@/page/tourist/index.vue')
    },
    {
        path: '/home',   
        name:'home',       
        component: () => import('@/page/index.vue'),
        children:[
            {
                path: 'publicTable',
                name: 'publicTable',
                component: () => import('@/page/publicTable/index.vue'),
            },
            {
                path:"publicOne",
                name: 'publicOne',
                component: () => import('@/page/pubicFiles/index.vue'),
            },
         
            {
                path:"regulate",
                name:"regulate",
                component: () => import('@/page/systemUser/index.vue'),
            },
            
        ]
    },
    {
        path: '/:error*', // 路由通配,兜底路由
        name: 'login',
        component:Login,
    }
      
]

const router = createRouter({
    history:createWebHistory(),
    routes
})
router.beforeEach((to, from, next) => {
    // 在导航之前执行的逻辑,可以用来进行权限控制等
    console.log('Before Each', to, from);
  
    // 如果需要导航到下一个路由,调用 next(),否则调用 next(false) 或者传递一个路由对象 next({ path: '/login' })
    next();
  });
  
  router.beforeResolve((to, from) => {
    // 在导航被确认之前执行的逻辑
    console.log('Before Resolve', to, from);
  });
  
  router.afterEach((to, from) => {
    // 在导航之后执行的逻辑,比如记录页面浏览历史
    console.log('After Each', to, from);
  });
export default router;


这三个函数是 Vue Router 提供的全局导航守卫:

  1. beforeEach(to, from, next):

    • 在每次路由导航触发前调用。
    • 参数 to 是即将要进入的路由对象,from 是当前导航正要离开的路由对象,next 是一个函数,调用它会继续执行导航过程。你可以在这个守卫中进行一些全局的导航前逻辑,如权限验证。
  2. beforeResolve(to, from):

    • 在导航被确认之前调用。
    • 类似于 beforeEach,但是在所有异步组件解析完之后被调用。可以在这里执行一些需要等到异步组件解析完后再进行的操作。
  3. afterEach(to, from):

    • 在每次路由导航完成后调用。
    • 可以在这里执行一些全局的导航后逻辑,如记录用户行为、埋点等。

这些导航守卫允许你在路由导航的不同阶段添加一些自定义的逻辑。在 beforeEach 中,你可以阻止或者修改导航;在 beforeResolve 中,你可以等待异步组件解析完成;在 afterEach 中,你可以执行一些导航后的操作。

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值