isNavigationFailure() - 检测导航失败
isNavigationFailure() 是一个实用的类型检测函数,专门用来判断一个值是否为导航失败对象,并可以进一步检测具体的失败类型。🔍
📋 函数签名
typescript
function isNavigationFailure(
error: any,
type?: NavigationFailureType
): boolean1
2
3
4
2
3
4
🎯 功能说明
这个函数就像是一个"导航失败检测器",帮你:
- 确认错误类型 - 判断一个错误是否是导航失败
- 分类失败原因 - 识别具体的失败类型(中止、取消、重复等)
- 简化错误处理 - 提供类型安全的错误检测方式
⚙️ 参数说明
error - 要检测的错误对象
| 类型 | 说明 |
|---|---|
any | 需要检测的错误对象,通常是导航操作的返回值 |
type - 具体的失败类型(可选)
| 类型 | 说明 |
|---|---|
NavigationFailureType | 具体的失败类型枚举值 |
📤 返回值
返回一个布尔值,表示检测结果:
true- 是导航失败(如果指定了类型,则是指定类型的失败)false- 不是导航失败
💡 实际应用示例
基础用法:检测是否是导航失败
javascript
import { isNavigationFailure } from 'vue-router'
router.push('/some-path').then(failure => {
if (isNavigationFailure(failure)) {
console.log('发生了导航失败!')
} else {
console.log('导航成功!')
}
})1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
检测特定类型的失败
javascript
import { isNavigationFailure, NavigationFailureType } from 'vue-router'
router.push('/admin').catch(failure => {
if (isNavigationFailure(failure, NavigationFailureType.cancelled)) {
console.log('导航被守卫取消了!')
}
if (isNavigationFailure(failure, NavigationFailureType.duplicated)) {
console.log('不能重复跳转到当前路由!')
}
})1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
错误处理策略
javascript
// 统一的错误处理函数
function handleNavigationError(error) {
if (isNavigationFailure(error)) {
switch (error.type) {
case NavigationFailureType.cancelled:
showToast('导航被取消')
break
case NavigationFailureType.duplicated:
showToast('已经是当前页面')
break
case NavigationFailureType.aborted:
showToast('导航被中断,请重试')
break
}
} else {
// 其他类型的错误
console.error('未知错误:', error)
}
}
// 使用示例
router.push('/target').catch(handleNavigationError)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
🎯 使用技巧
组合检测多个类型
javascript
// 检测是否是中止或取消类型的失败
const isAbortedOrCancelled = isNavigationFailure(failure,
NavigationFailureType.aborted | NavigationFailureType.cancelled)1
2
3
2
3
在导航守卫中使用
javascript
router.beforeEach((to, from, next) => {
// 某些条件下取消导航
if (!hasPermission(to)) {
next(false) // 这将产生 cancelled 类型的失败
} else {
next()
}
})
// 在错误处理中检测
router.push('/restricted').catch(failure => {
if (isNavigationFailure(failure, NavigationFailureType.cancelled)) {
console.log('权限不足,导航被取消')
}
})1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
🔗 相关 API
NavigationFailureType- 导航失败类型枚举- 导航守卫相关的错误处理
💡 专业建议:在生产环境中,建议对重要的导航操作进行失败检测,提供更好的用户体验和错误恢复机制。