fangchaolong
文章57
标签24
分类10
vue-router中的路由钩子函数基本用法汇总

vue-router中的路由钩子函数基本用法汇总

最近学习一下,vue-router的路由钩子函数

路由钩子函数分为三种类型如下:

第一种:全局钩子函数。


    router.beforeEach((to, from, next) => {
    console.log('beforeEach')
    //next() //如果要跳转的话,一定要写上next()
    //next(false) //取消了导航
    next() //正常跳转,不写的话,不会跳转
  })
  router.afterEach((to, from) => { // 举例: 通过跳转后改变document.title
    if( to.meta.title ){
      window.document.title = to.meta.title //每个路由下title
    }else{
      window.document.title = '默认的title'
    }
  })

第二种:针对单个路由钩子函数


    beforeEnter(to, from, next){
    console.log('beforeEnter')
    next() //正常跳转,不写的话,不会跳转
  }

第三种:组件级钩子函数


    beforeRouteEnter(to, from, next){ // 这个路由钩子函数比生命周期beforeCreate函数先执行,所以this实例还没有创建出来
    console.log("beforeRouteEnter")
    console.log(this) //这时this还是undefinde,因为这个时候this实例还没有创建出来
    next((vm) => { //vm,可以这个vm这个参数来获取this实例,接着就可以做修改了
      vm.text = '改变了'
    })
  },
  beforeRouteUpdate(to, from, next){//可以解决二级导航时,页面只渲染一次的问题,也就是导航是否更新了,是否需要更新
    console.log('beforeRouteUpdate')
    next();
  },
  beforeRouteLeave(to, from, next){// 当离开组件时,是否允许离开
    next()
  }

无以生计,卖文苟延

微信
支付宝