通常一个导航守卫函数中会发生这四件事之一:
1.通过调用 return false 中断了这次导航
2.通过返回一个新的位置,重定向到其他地方 (例如,return ‘/login’)
3.正常导航到指定路由
4.抛出了一个 Error
检测导航故障
可以使用vue-router提供的一些API来检测导航故障。vue-router为路由导航异常的检测提供了isNavigationFailure函数,这个函数允许你判断一个错误是否来自于导航过程。
import { isNavigationFailure, NavigationFailureType } from 'vue-router' // 尝试访问某个页面
router.push('/some-page').catch(failure => { if (isNavigationFailure(failure, NavigationFailureType.aborted)) { // 导航被拦截并返回了false console.log('Navigation aborted') } else if (isNavigationFailure(failure, NavigationFailureType.cancelled)) { // 在导航完成之前又产生了一次新的导航 console.log('Navigation cancelled') } else if (isNavigationFailure(failure, NavigationFailureType.duplicated)) { // 导航被阻止,已经在目标位置了 console.log('Navigation duplicated') } else { // 不是导航故障的错误,可能是其他类型的错误 console.error('Unknown error', failure) }
})const navigationResult = await router.push('/my-profile')if (navigationResult) {// 导航被阻止
} else {// 导航成功 (包括重新导航的情况)this.isMenuOpen = false
}
全局导航故障
router.afterEach((to, from, failure) => {if (failure) {sendToAnalytics(to, from, failure)}
})
导航故障的属性
所有的导航失败都会暴露 to 和 from 属性,以反映失败导航的当前位置和目标位置:
// 正在尝试访问 admin 页面
router.push('/admin').then(failure => {if (isNavigationFailure(failure, NavigationFailureType.aborted)) {failure.to.path // '/admin'failure.from.path // '/'}
})
检测重定向
当在导航守卫中返回一个新的位置时,我们会触发一个新的导航,覆盖正在进行的导航。与其他返回值不同的是,重定向不会阻止导航,而是创建一个新的导航。因此,通过读取路由地址中的 redirectedFrom 属性,对其进行不同的检查:
await router.push('/my-profile')
if (router.currentRoute.value.redirectedFrom) {// redirectedFrom 是解析出的路由地址,就像导航守卫中的 to和 from
}