vue-router构子函数

249 阅读1分钟

vue-router构子函数

1.路由独享构子

  {
    path:'/home/:id',
    name: 'Home',
    component: Home,
    beforeEnter: (to, from, next) => {
      console.log('我是home页面的路由独享钩子');
      next();
    }
  },

2.全局路由的构子函数

  • beforeEach路由跳转前触发
  • beforeResolve类似于beforeEach也是路由跳转前触发
  • beforeEach是在路由跳转完成后触发
router.beforeEach((to,from,next)=>{
  next()
 
  
})

router.beforeResolve((to,from,next)=>{
  next()
})

router.afterEach((to,from)=>{
  // console.log('afterEach')
})

组件构子函数

  • beforeRouteEnter路由进入组件之前调用
  • beforeRouteUpdate当前路由改变时,并且该组件被复用时调用,可以通过this访问实例。
  • beforeRouteLeave导航离开该组件的对应路由时调用
 beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
    console.log(this);
    console.log('beforeRouteEnter')
    next()
  },
  beforeRouteUpdate(to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    // console.log(this.$route.params.id);
    console.log(to.params.id)
    console.log('beforeRouteUpdate');
    console.log(this.list.filter(item => item.id == to.params.id), '------');
    // 当跳转路径一样,参数不一样时,我们需要用到这个路由钩子来解决bug,通过to拿到你要跳转的不一样的参数,然后向后台重新请求数据赋值给这个组件
    next()
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    console.log(this)
    console.log('beforeRouteLeave');
    next()
  },