vue 钩子函数的初接触

♀尐吖头ヾ 提交于 2019-12-04 06:57:46

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

 

 
 

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!