router.beforeEach与beforeRouteEnter的区别

使用场景

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

定义

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

两种函数:

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

2.router.afterEach(function(to,form))/在跳转之后判断/

全局钩子函数

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

// router=>index.js配置全局路由钩子
router.beforeEach((to, from, next) => {
if(to.fullPath==='/app'){
     next('login')
}else{
     next()
} 
}); 

beforeEach函数有三个参数

  • to:router即将进入的路由对象
  • from:当前导航即将离开的路由
  • next:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。

afterEach函数不用传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: {}

PS:在使用vue-router beforeEach钩子时,你也许会遇到如下问题:

router.beforeEach((to, from, next) => {
//判断登录状态简单实例
var userInfo = window.localStorage.getItem(‘token');
if (userInfo) {
next();
} else {
next('/login');
}
})

然后你会发现出现如下错误:出现dead loop错误

router.beforeEach((to, from, next) => {
var userInfo = window.localStorage.getItem(‘token');//获取浏览器缓存的用户信息
if(userInfo){ //如果有就直接到首页咯
next();
} else {
if(to.path=='/login'){ //如果是登录页面路径,就直接next()
next();
} else { //不然就跳转到登录;
next('/login');
}
}
})

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()
}

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。