vue中路由守卫及运用

每个守卫方法接收三个参数:
to:即将要进入的目标路由对象
from:当前导航正要离开的路由
next:执行下一步
next()用法:
1.next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
2.next({ name: ‘Login’ })或next({ path: ‘/’ }): 跳转到某个地址。
3.next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
4.next(error): 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

1.全局路由守卫

(1)全局前置守卫

import router from './router'
router.beforeEach((to, from, next) => {
    
    
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    
    
    document.title = to.meta.title
  }
  next() 
  //全局参数透传
  if (!to.query.product) {
    
    
    next({
    
    
      path: to.path,
      query: {
    
    
        product: 'xxx'
      }
    });
  } else {
    
    
    next();
  }
})

(2)全局解析守卫
与全局前置守卫区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用

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

(3)全局后置守卫

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

2.路由独享的守卫

用法与全局路由守卫一致。只是将其写进一个路由对象中,只在当前这个路由中起作用

routes: [
  {
    
    
    path: "/home",
    component: Home,
    beforeEnter: (to, from, next) => {
    
    
      // ...
    }
  }
];

3.组件内的守卫

不可以访问组件实例 this,因为在守卫执行前,组件实例还没被创建
通过next()回调函数访问
注意:被监听的组件要有子路由,否则以下方法都不执行

beforeRouteEnter (to, from, next) {
    
    
  next(vm => {
    
    
    // 通过 `vm` 访问组件实例
  })
}

可以访问组件实例 this

beforeRouteUpdate (to, from, next) {
    
    
  this.name = to.params.name
  next()
}
//之前用的是
watch: {
    
    
    $route(to,from){
    
    
      if(to.path.includes("myAct")){
    
    
        this.getData()
      }
   }
},

这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消。可以访问组件实例 this

beforeRouteLeave (to, from, next) {
    
    
  const answer = window.confirm('确定离开当前页面吗?')
  if (answer) {
    
    
    next()
  } else {
    
    
    next(false)
  }
}

猜你喜欢

转载自blog.csdn.net/m0_48076809/article/details/109191687
今日推荐