Skip to content

RouterHistory Interface | Vue Router

RouterHistory defines the contract for history management implementations. It abstracts URL manipulation and navigation for different history strategies. 📚

📋 Interface Definition

typescript
interface RouterHistory {
  readonly router: Router | null
  readonly base: string
  readonly location: RouteLocationNormalized
  readonly state: HistoryState
  
  push(to: RouteLocationRaw): Promise<void>
  replace(to: RouteLocationRaw): Promise<void>
  go(delta: number): void
  back(): void
  forward(): void
  
  listen(callback: HistoryListener): () => void
  destroy(): void
}

🎯 Purpose and Usage

The RouterHistory interface standardizes history management across different implementations:

  • HTML5 History (createWebHistory()) - Clean URLs, requires server config
  • Hash History (createWebHashHistory()) - Works with static servers
  • Memory History (createMemoryHistory()) - For testing/SSR

🔍 Core Properties

router - Associated Router

Reference to the router instance.

base - Base URL

Application base path (e.g., "/my-app/").

location - Current Location

Normalized route location with reactive properties.

state - History State

Current history state object.

💡 Navigation Methods

push() - Add to History Stack

typescript
await history.push('/new-page')
await history.push({ name: 'user', params: { id: '123' } })

replace() - Replace Current Entry

typescript
await history.replace('/updated-page') // No back button history
typescript
history.go(-2)    // Go back 2 steps
history.back()    // Browser back equivalent  
history.forward() // Browser forward equivalent

🔧 Lifecycle Methods

listen() - History Change Listener

typescript
const unsubscribe = history.listen((location, action) => {
  console.log('History changed:', action, location.path)
})

// Clean up later
unsubscribe()

destroy() - Resource Cleanup

Cleans up event listeners and resources.

💡 Practical Examples

History Analytics

typescript
history.listen((location, action) => {
  analytics.track('navigation', {
    action,
    path: location.path,
    timestamp: Date.now()
  })
})

State Management

typescript
// Store data in history state
const currentState = history.state
window.history.replaceState({
  ...currentState,
  customData: 'value'
}, '')

💡 Pro Tip: Choose history implementation based on deployment environment. Use hash history for static hosting, HTML5 history for server-controlled deployments.

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