vuerouter的几个钩子函数

主要介绍一下vuerouter的几种钩子函数:

一、全局钩子(2个)

 每次跳转路由时都会执行这个钩子函数,由router调用

1、beforeEach(to,from,next)

  页面加载之前执行,有三个参数

router.beforeEach((to, from, next) => {
  if (to.matched.length === 0) {
    from.name ? next({ name : from.name }) : next('/')
  } else {
    next()
  }
})

2、afterEach(to,from)

  页面加载之后执行,有两个参数,没有next

router.afterEach((to,from) => {
  console.log(to);//到达的路由
  console.log(from);//离开的路由
})

to:到哪个路由去

from:从哪个路由来

next:判断是否进入

  next有几种形式,一一解释一下

   1、next():可以跳转到目标路由

   2、next(false):不可以跳转,回到源路由

   3、next(/path):中断当前跳转路径,跳转到/path指定的路由

   4、next(error):当前跳转终止,并执行router.onError中的回调函数

小栗子:可以做一些页面跳转前的认证,对一些需要登录的页面进行拦截,跳转到登录页面

router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {
        //判断该路由是否需要登录权限
        if (cookies('token')) {
            //通过封装好的cookies读取token,如果存在,name接下一步如果不存在,那跳转回登录页
            next()//不要在next里面加"path:/",会陷入死循环
        }
        else {
            next({
                path: '/login',
                query: {redirect: to.fullPath}//将跳转的路由path作为参数,登录成功后跳转到该路由
            })
        }
    }
    else {
        next()
    }
})

二、单个路由钩子(2个)

只要用于指定某个特定路由跳转时的逻辑,写在某个路由配置内部

1、beforeEnter()

2、beforeLeave()

const routes = [
    {
        path: '/home',
        component: Home
        
        beforeEnter;(to,from,next) => {
            console.log(to)
        }

        beforeLeave:(to,from,next) => {
            console.log(from)
        }
    }

三、组件内部钩子(3个)

在组件内使用

1、beforeRouterEnter()

2、beforeRouterLeave()

3、beforeRouterUpdate():下一次更新之前

beforeRouterEnter(to,from,next){
    console.log(to)
}
const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当钩子执行前,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
 
  }

小栗子1:当页面中有需要保存的信息时,阻止页面进行跳转,让用户先保存信息

beforeRouteLeave (to, from, next) {
 //判断是否弹出框的状态和保存信息与否
 if (this.dialogVisibility === true) {
    this.dialogVisibility = false //关闭弹出框
    next(false) //回到当前页面, 阻止页面跳转
  }else if(this.saveMessage === false) {
    alert('请保存信息后退出!') //弹出警告
    next(false) //回到当前页面, 阻止页面跳转
  }else {
    next() //否则允许跳转
  }

小栗子2:在用户关闭页面之前保存信息到vuex或session里

beforeRouteLeave (to, from, next) {
    localStorage.setItem(name, content); //保存到localStorage中
    next()
}

注意他们的使用方式,仔细看

  • 3
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值