Skip to content

RouteLocationRaw Type Alias | Vue Router

RouteLocationRaw is a type alias that represents raw route locations in various formats that can be used for navigation. It's the most flexible type for specifying route destinations. 🎯

📋 Type Definition

typescript
type RouteLocationRaw = 
  | string 
  | RouteLocationPathRaw 
  | RouteLocationNamedRaw

🎯 Purpose and Usage

The RouteLocationRaw type alias defines all valid formats for specifying route locations in Vue Router navigation methods. It provides maximum flexibility while maintaining type safety.

Supported Formats:

  • String paths - Simple path strings like "/user/123"
  • Path objects - Objects with path and parameters
  • Named routes - Objects with route name and parameters

🔍 Type Structure

String Paths

Simple path strings for direct navigation.

typescript
// Simple path navigation
router.push('/user/123')
router.push('/search?q=vue')

RouteLocationPathRaw Objects

Objects with path and additional options.

typescript
// Path-based navigation with options
router.push({
  path: '/user/123',
  query: { tab: 'profile' },
  hash: '#section'
})

RouteLocationNamedRaw Objects

Objects using route names for navigation.

typescript
// Named route navigation
router.push({
  name: 'user-profile',
  params: { id: '123' },
  query: { tab: 'settings' }
})

💡 Practical Usage Examples

Basic Navigation Patterns

typescript
import type { RouteLocationRaw } from 'vue-router'

// Different ways to specify route locations
const navigationExamples: RouteLocationRaw[] = [
  // String path (simplest)
  '/home',
  
  // Path with query parameters
  '/search?q=vue+router',
  
  // Path object with full control
  {
    path: '/user/:id',
    params: { id: '123' },
    query: { tab: 'profile' },
    hash: '#bio'
  },
  
  // Named route navigation
  {
    name: 'user-profile',
    params: { id: '123' }
  }
]

// Using in navigation methods
async function navigateToProfile(userId: string) {
  const location: RouteLocationRaw = {
    name: 'user-profile',
    params: { id: userId }
  }
  await router.push(location)
}

Dynamic Route Location Creation

typescript
class RouteLocationBuilder {
  // Create search location with filters
  static createSearchLocation(
    query: string, 
    filters?: Record<string, string>
  ): RouteLocationRaw {
    if (filters) {
      return {
        path: '/search',
        query: { q: query, ...filters }
      }
    }
    return `/search?q=${encodeURIComponent(query)}`
  }
  
  // Create user profile location
  static createUserProfileLocation(
    userId: string, 
    tab?: string
  ): RouteLocationRaw {
    const baseLocation = {
      name: 'user-profile' as const,
      params: { id: userId }
    }
    
    if (tab) {
      return {
        ...baseLocation,
        query: { tab }
      }
    }
    
    return baseLocation
  }
  
  // Create paginated list location
  static createPaginatedLocation(
    routeName: string, 
    page: number, 
    itemsPerPage: number = 10
  ): RouteLocationRaw {
    return {
      name: routeName,
      query: { 
        page: page.toString(),
        limit: itemsPerPage.toString()
      }
    }
  }
}

🔧 Advanced Patterns

Type-Safe Navigation Utilities

typescript
// Define application-specific route locations
type AppRouteLocations = 
  | { type: 'home' }
  | { type: 'user-profile'; userId: string; tab?: string }
  | { type: 'search'; query: string; filters?: SearchFilters }
  | { type: 'admin'; section: string }

class AppNavigation {
  static toRouteLocation(location: AppRouteLocations): RouteLocationRaw {
    switch (location.type) {
      case 'home':
        return '/'
        
      case 'user-profile':
        return {
          name: 'user-profile',
          params: { id: location.userId },
          ...(location.tab && { query: { tab: location.tab } })
        }
        
      case 'search':
        return {
          path: '/search',
          query: { 
            q: location.query,
            ...location.filters
          }
        }
        
      case 'admin':
        return `/admin/${location.section}`
    }
  }
}

// Usage
const profileLocation = AppNavigation.toRouteLocation({
  type: 'user-profile',
  userId: '123',
  tab: 'settings'
})

Route Location Validation

typescript
class RouteLocationValidator {
  static isValidRouteLocation(location: any): location is RouteLocationRaw {
    if (typeof location === 'string') {
      return this.isValidPathString(location)
    }
    
    if (typeof location === 'object' && location !== null) {
      return this.isValidRouteObject(location)
    }
    
    return false
  }
  
  private static isValidPathString(path: string): boolean {
    return path.startsWith('/') && path.length > 0
  }
  
  private static isValidRouteObject(obj: any): boolean {
    // Must have either path or name
    if (!obj.path && !obj.name) {
      return false
    }
    
    // Path must be string if present
    if (obj.path && typeof obj.path !== 'string') {
      return false
    }
    
    // Name must be valid if present
    if (obj.name && typeof obj.name !== 'string' && 
        typeof obj.name !== 'symbol') {
      return false
    }
    
    return true
  }
}

🚨 Important Considerations

typescript
// RouteLocationRaw works with all navigation methods
const location: RouteLocationRaw = {
  name: 'user-profile',
  params: { id: '123' }
}

// All these accept RouteLocationRaw
router.push(location)
router.replace(location) 
router.resolve(location)
router.back() // Note: back() doesn't take parameters

// Also works with router-link
const routerLinkProps = {
  to: location
}

Type Safety with Route Parameters

typescript
// For better type safety, use route name with params
interface RouteParams {
  userProfile: { id: string }
  search: { q: string }
}

// Now TypeScript will validate parameters
router.push({
  name: 'user-profile',
  params: { id: '123' } // ✅ Correct
})

router.push({
  name: 'user-profile',
  params: { userId: '123' } // ❌ TypeScript error
})

📚 Best Practices

Consistent Navigation Patterns

typescript
// ✅ Good: Use factory functions for common navigations
const navigations = {
  toHome: () => '/' as RouteLocationRaw,
  toUserProfile: (userId: string) => ({
    name: 'user-profile',
    params: { id: userId }
  } as RouteLocationRaw),
  toSearch: (query: string) => ({
    path: '/search',
    query: { q: query }
  } as RouteLocationRaw)
}

// ✅ Good: Validate locations before navigation
async function safeNavigate(location: RouteLocationRaw) {
  if (!RouteLocationValidator.isValidRouteLocation(location)) {
    throw new Error('Invalid route location')
  }
  
  try {
    await router.push(location)
  } catch (error) {
    console.error('Navigation failed:', error)
  }
}

// ❌ Avoid: Mixing string and object formats inconsistently
const inconsistentLocation = {
  path: '/user/123',
  name: 'user-profile' // Conflicting information
}

Error Handling

typescript
class NavigationErrorHandler {
  static async handleNavigation(
    location: RouteLocationRaw,
    options?: { replace?: boolean }
  ): Promise<boolean> {
    try {
      if (options?.replace) {
        await router.replace(location)
      } else {
        await router.push(location)
      }
      return true
    } catch (error) {
      console.error('Navigation error:', error)
      
      // Provide user feedback based on error type
      if (this.isNavigationFailure(error)) {
        this.showNavigationError(error)
      } else {
        this.showGenericError()
      }
      
      return false
    }
  }
}

💡 Pro Tip: Use RouteLocationRaw for maximum flexibility in route navigation. For type-safe navigation with specific routes, consider creating application-specific type aliases that extend or narrow down this type.

🚀 Vue Router - 让前端路由变得简单而强大 | 构建现代化单页应用的最佳选择