vue钩子函数之拦截器 beforeEach和afterEach

本文详细介绍了Vue中路由钩子的使用方法,包括全局钩子、特定路由钩子及组件内的钩子。通过实例展示了如何在路由跳转前后执行特定操作,如权限验证等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在路由跳转的时候,我们需要一些权限判断或者其他操作。这个时候就需要使用路由的钩子函数。

定义:路由钩子主要是给使用者在路由发生变化时进行一些特殊的处理而定义的函数。

总体来讲vue里面提供了三大类钩子,两种函数 1、全局钩子 2、某个路由的钩子 3、组件内钩子

两种函数:

1. Vue.beforeEach(function(to,form,next){}) /*在跳转之前执行*/

2. Vue.afterEach(function(to,form)}{}) /*在跳转之后判断*/
全局钩子函数

顾名思义,它是对全局有效的一个函数

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'sideBar',
      component: sideBar,
      children:[
        {
          path:'/',
          name:'sort',
          component:sort
        },
        {
          path:'/addNewSort',
          name:'addNewSort',
          component:addNewSort
        },
        {
          path:'/notSend',
          name:'notSend',
          component:notSend
        },
        {
          path:'/sended',
          name:'sended',
          component:sended
        },
    }
  ]
})

router.beforeEach((to,from,next)=>{
  // console.log("to:",to);      // router即将进入的路由对象
  // console.log("from:",from);  // 当前导航即将离开的路由
  // console.log("next:",next);  // Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。
  if(to.name=='notSend'){
    next({
      name:'sort'
    })
    return
  }
  next()
})

export default router
某个路由的钩子函数

顾名思义,它是写在某个路由里头的函数,本质上跟组件内函数没有区别。

const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: Login,
      beforeEnter: (to, from, next) => {
        // ...
      },
      beforeLeave: (to, from, next) => {
        // ...
      }
    }
  ]
})
路由组件的钩子

可以在路由组件内直接定义以下路由导航钩子

beforeRouteEnter
beforeRouteUpdate (2.2 新增)
beforeRouteLeave

这里简单说下钩子函数的用法:它是和data,methods平级的。

beforeRouteLeave(to, from, next) {
    next()
},
beforeRouteEnter(to, from, next) {
    next()
},
beforeRouteUpdate(to, from, next) {
    next()
},
data:{},
method: {}

 


更多专业前端知识,请上【猿2048】www.mk2048.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值