RouteLocationRaw 类型别名 | Vue Router API
概述
RouteLocationRaw 是 Vue Router 中最重要的类型别名之一,它定义了所有可以传递给导航方法(如 router.push()、router.replace())的有效路由位置类型。理解这个类型对于正确使用 Vue Router 的导航功能至关重要。
类型定义
typescript
type RouteLocationRaw =
| string
| RouteQueryAndHash
| RouteLocationPathRaw
| RouteLocationNamedRaw具体类型说明
1. 字符串形式(String)
最简单的路由位置形式,直接使用路径字符串。
typescript
// 基本路径
'/home'
'/user/123'
'/search?q=vue'
// 带哈希的路径
'/page#section'
'/about#contact'使用示例:
javascript
// 编程式导航
router.push('/home')
router.replace('/user/123')
// RouterLink 组件
<router-link to="/about">关于</router-link>2. RouteQueryAndHash 对象
包含路径、查询参数和哈希的完整路由位置对象。
typescript
interface RouteQueryAndHash {
path: string
query?: LocationQuery
hash?: string
}使用示例:
javascript
// 带查询参数和哈希
router.push({
path: '/search',
query: { q: 'vue', category: 'docs' },
hash: '#results'
})
// 仅路径和查询参数
router.push({
path: '/user',
query: { id: 123, tab: 'profile' }
})
// 仅路径和哈希
router.push({
path: '/page',
hash: 'section-2'
})3. RouteLocationPathRaw 对象
基于路径的路由位置,支持参数替换。
typescript
interface RouteLocationPathRaw extends RouteQueryAndHash {
params?: LocationParams
}使用示例:
javascript
// 路径参数替换
router.push({
path: '/user/:id/posts/:postId',
params: { id: 123, postId: 456 }
})
// 结果: /user/123/posts/456
// 结合查询参数
router.push({
path: '/search/:category',
params: { category: 'vue' },
query: { sort: 'date' }
})
// 结果: /search/vue?sort=date4. RouteLocationNamedRaw 对象
基于命名路由的导航,提供更好的类型安全和重构友好性。
typescript
interface RouteLocationNamedRaw extends RouteQueryAndHash {
name: string
params?: LocationParams
}使用示例:
javascript
// 命名路由导航
router.push({
name: 'user-profile',
params: { id: 123 }
})
// 带查询参数的命名路由
router.push({
name: 'search',
params: { category: 'docs' },
query: { q: 'router' }
})
// 仅使用名称
router.push({ name: 'home' })实际应用场景
场景 1:用户界面导航
javascript
// 用户资料页面导航
function navigateToUserProfile(userId, tab = 'profile') {
router.push({
name: 'user-profile',
params: { id: userId },
query: { tab }
})
}
// 搜索功能
function performSearch(query, filters = {}) {
router.push({
path: '/search',
query: {
q: query,
...filters
}
})
}
// 页面内锚点跳转
function scrollToSection(sectionId) {
router.push({
path: router.currentRoute.value.path,
hash: sectionId
})
}场景 2:表单处理和工作流
javascript
// 多步骤表单导航
class MultiStepForm {
constructor(router) {
this.router = router
this.steps = ['info', 'details', 'confirmation']
}
// 下一步
nextStep(currentStep, formData) {
const currentIndex = this.steps.indexOf(currentStep)
const nextStep = this.steps[currentIndex + 1]
if (nextStep) {
router.push({
name: 'form-step',
params: { step: nextStep },
query: { ...formData }
})
}
}
// 上一步
previousStep(currentStep) {
const currentIndex = this.steps.indexOf(currentStep)
const prevStep = this.steps[currentIndex - 1]
if (prevStep) {
router.back() // 或使用具体路径
}
}
}场景 3:电子商务应用
javascript
// 产品导航和过滤
class ProductNavigation {
constructor(router) {
this.router = router
}
// 浏览产品分类
browseCategory(categoryId, filters = {}) {
router.push({
name: 'category',
params: { id: categoryId },
query: {
sort: filters.sort || 'popular',
price_min: filters.minPrice,
price_max: filters.maxPrice,
in_stock: filters.inStock
}
})
}
// 产品详情页
viewProduct(productId, variant = null) {
const location = {
name: 'product-detail',
params: { id: productId }
}
if (variant) {
location.query = { variant }
}
router.push(location)
}
// 购物车操作
addToCartAndNavigate(productId, quantity = 1) {
// 添加商品到购物车
cart.addItem(productId, quantity)
// 导航到购物车或继续购物
router.push({
name: 'cart',
query: { added: productId }
})
}
}类型安全实践(TypeScript)
1. 定义类型安全的路由映射
typescript
// 路由映射类型定义
interface AppRouteMap {
'home': {
params?: never
query?: { tab?: string }
}
'user-profile': {
params: { id: string }
query?: { section?: 'info' | 'posts' | 'photos' }
}
'search': {
params?: { category?: string }
query: { q: string; sort?: string }
}
}
// 类型安全的导航函数
function typedPush<T extends keyof AppRouteMap>(
name: T,
options: {
params?: AppRouteMap[T]['params']
query?: AppRouteMap[T]['query']
} = {}
) {
return router.push({
name,
...options
} as RouteLocationNamedRaw)
}
// 使用示例
typedPush('user-profile', {
params: { id: '123' },
query: { section: 'posts' }
})2. 路由位置验证
typescript
// 路由位置验证器
function isValidRouteLocation(location: RouteLocationRaw): boolean {
if (typeof location === 'string') {
return location.startsWith('/')
}
if ('path' in location) {
return location.path.startsWith('/')
}
if ('name' in location) {
return typeof location.name === 'string'
}
return false
}
// 安全导航包装器
async function safeNavigate(location: RouteLocationRaw) {
if (!isValidRouteLocation(location)) {
throw new Error('无效的路由位置')
}
return router.push(location)
}高级用法
1. 路由位置转换
typescript
// 路由位置标准化
function normalizeRouteLocation(
location: RouteLocationRaw
): RouteLocationNamedRaw | RouteLocationPathRaw {
if (typeof location === 'string') {
return { path: location }
}
return location
}
// URL 参数编码处理
function encodeRouteParams(location: RouteLocationRaw): RouteLocationRaw {
if (typeof location === 'string') {
return location
}
if ('query' in location && location.query) {
const encodedQuery = Object.fromEntries(
Object.entries(location.query).map(([key, value]) => [
key,
typeof value === 'string' ? encodeURIComponent(value) : value
])
)
return {
...location,
query: encodedQuery
}
}
return location
}2. 历史记录管理
typescript
// 带状态的路由位置
interface StatefulRouteLocation extends RouteLocationRaw {
state?: Record<string, any>
}
// 状态管理集成
class RouteStateManager {
private stateMap = new Map<string, any>()
pushWithState(location: RouteLocationRaw, state: any) {
const stateKey = Date.now().toString()
this.stateMap.set(stateKey, state)
const statefulLocation: StatefulRouteLocation = {
...location,
state: { key: stateKey }
}
return router.push(statefulLocation)
}
getCurrentState() {
const currentState = router.currentRoute.value.state
if (currentState?.key) {
return this.stateMap.get(currentState.key)
}
return null
}
}最佳实践
1. 统一导航模式
javascript
// 导航服务类
class NavigationService {
constructor(router) {
this.router = router
}
// 统一的主页导航
goHome() {
return this.router.push({ name: 'home' })
}
// 统一的返回逻辑
goBack(fallbackRoute = '/') {
if (window.history.length > 1) {
this.router.back()
} else {
this.router.push(fallbackRoute)
}
}
// 智能搜索导航
search(query, options = {}) {
const location = {
name: 'search',
query: { q: query }
}
if (options.category) {
location.params = { category: options.category }
}
if (options.filters) {
location.query = { ...location.query, ...options.filters }
}
return this.router.push(location)
}
}2. 错误处理和重试
javascript
// 带错误处理的路由导航
async function robustNavigate(location: RouteLocationRaw, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const result = await router.push(location)
if (result) {
console.warn(`导航被阻止 (尝试 ${attempt}):`, result)
if (attempt === maxRetries) {
throw new Error(`导航失败: ${result.type}`)
}
continue
}
return true
} catch (error) {
console.error(`导航错误 (尝试 ${attempt}):`, error)
if (attempt === maxRetries) {
throw error
}
}
}
}注意事项
- 参数编码 - 注意 URL 参数的正确编码和解码
- 路径规范化 - 确保路径格式正确(以
/开头) - 类型安全 - 使用 TypeScript 增强类型检查
- 性能考虑 - 避免频繁的路由导航操作
🎯 总结:
RouteLocationRaw类型提供了灵活的路由导航方式。通过掌握各种路由位置形式,你可以构建出更加健壮和用户友好的单页应用程序。