导航结果

每次导航操作都会返回一个 NavigateResult 对象,它包含了导航的最终状态和相关信息。通过检查导航结果,你可以判断导航是否成功、是否被守卫拦截、是否发生了重定向等。

NavigateResult 对象包含导航的状态和相关信息,主要属性包括:

  • state — 导航状态码(位标志)
  • to — 目标路由位置(可能为 null
  • from — 来源路由位置
  • redirectFrom — 重定向来源(可选)
  • message — 状态描述信息

完整类型定义参见 NavigateResult API

NavState 是一组位标志枚举,支持通过位运算组合检查多个状态:

状态说明
success1导航成功
aborted2导航被守卫拦截
cancelled4导航被新导航取消
duplicated8重复导航
notfound16路由未找到
external32外部链接跳转

完整类型定义参见 NavState API

辅助函数

vitarx-router 提供了两个辅助函数,方便你判断导航结果:

hasSuccess(result) 检查导航是否成功,hasState(result, state) 按位检查导航状态。

完整 API 参见 hasSuccess / hasState

处理导航失败

根据不同的失败原因,你可以采取不同的处理策略:

ts
import { hasSuccess, hasState, NavState } from 'vitarx-router'

const result = await router.push('/protected')

// 检查是否成功
if (hasSuccess(result)) {
  console.log('导航成功')
} else {
  // 根据具体状态处理
  if (hasState(result, NavState.aborted)) {
    console.log('导航被守卫拦截:', result.message)
  }

  if (hasState(result, NavState.notfound)) {
    console.log('页面不存在:', result.message)
  }

  if (hasState(result, NavState.duplicated)) {
    console.log('已在当前页面')
  }

  if (hasState(result, NavState.cancelled)) {
    console.log('导航被新的导航取代')
  }
}

完整示例

ts
import { createRouter, hasSuccess, hasState, NavState } from 'vitarx-router'

const router = createRouter({
  mode: 'hash',
  routes: [
    { path: '/', component: Home },
    { path: '/user/{id}', index: 'user', component: User },
    { path: '/login', component: Login }
  ]
})

// 导航到用户页面
async function navigateToUser(id: string) {
  const result = await router.push({ index: 'user', params: { id } })

  if (hasSuccess(result)) {
    console.log('成功导航到:', result.to.fullPath)
  } else if (hasState(result, NavState.notfound)) {
    console.warn('用户页面不存在')
    router.replace('/404')
  } else if (hasState(result, NavState.aborted)) {
    console.warn('导航被拦截,可能需要登录')
    router.push('/login')
  }
}

// 检查重定向
async function checkRedirect() {
  const result = await router.push('/old-path')

  if (result.redirectFrom) {
    console.log(`从 #123;result.redirectFrom.fullPath} 重定向到了 #123;result.to.fullPath}`)
  }
}

API 参考导航 API