The main changes in Vue Router 4
Vue Router 4 is a major version upgrade of Vue.js's official routing library, released in sync with Vue 3. It has undergone a comprehensive refactoring in terms of API design, feature implementation, and performance optimization, while maintaining continuity in core routing concepts. Below is an analysis of its key changes across multiple dimensions.
Changes in Route Creation
Vue Router 4 no longer uses the new Router()
constructor, instead adopting the createRouter
factory function. This change aligns with Vue 3's Composition API style:
// Vue Router 3 syntax
const router = new VueRouter({
routes: [...]
})
// Vue Router 4 syntax
import { createRouter } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [...]
})
The history mode is now imported via separate functions:
createWebHistory()
corresponds to the original history modecreateWebHashHistory()
corresponds to the hash modecreateMemoryHistory()
is used for SSR scenarios
Upgraded Route Matching Syntax
The dynamic route matching syntax has undergone significant adjustments, replacing the original implementation with the path-to-regexp
library:
// Legacy syntax
{ path: '/user/:id(\\d+)' }
// New syntax
{
path: '/user/:id',
regex: /^\d+$/ // Uses regex to validate parameters
}
The wildcard route *
has been removed and replaced with custom regex:
// Alternative
{ path: '/:path(.*)*', component: NotFound }
Refactored Navigation Guard API
The navigation guard system has been completely overhauled, deeply integrating with the Composition API:
// Global guard changes
router.beforeEach((to, from) => {
// Return false to cancel navigation
// Can return a route path string or route location object
})
// In-component guards now use Composition API style
import { onBeforeRouteLeave } from 'vue-router'
setup() {
onBeforeRouteLeave((to, from) => {
// Leave guard logic
})
}
A new beforeResolve
guard timing has been added, executing after beforeEach
and before afterEach
.
Typed Route Meta Fields
The route meta field meta
now supports strong typing:
declare module 'vue-router' {
interface RouteMeta {
requiresAuth?: boolean
transitionName?: string
}
}
const routes: RouteRecordRaw[] = [
{
path: '/admin',
meta: { requiresAuth: true } // Now type-checked
}
]
Improved Dynamic Routing API
APIs for adding and removing routes have become more intuitive:
// Add a single route
router.addRoute({
path: '/new',
component: NewPage
})
// Add nested routes
router.addRoute('parent', {
path: 'child',
component: Child
})
// Remove a route
const removeRoute = router.addRoute(routeRecord)
removeRoute() // Removes the route
New methods hasRoute()
and getRoutes()
have been added for route detection and retrieval.
Changes to Scroll Behavior API
The scroll behavior configuration now returns an object structure consistent with native DOM APIs:
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition // Preserves native scroll position
}
return { top: 0 } // Uses modern scroll API format
}
})
Route Lazy Loading Syntax
Code splitting is implemented using Vue 3's defineAsyncComponent
:
// Vue Router 4 recommended approach
const UserDetails = () => import('./views/UserDetails.vue')
// Or using defineAsyncComponent
import { defineAsyncComponent } from 'vue'
const UserDetails = defineAsyncComponent(() =>
import('./views/UserDetails.vue')
)
Named Routes and Redirects
The usage of named routes has been adjusted, and redirects support more flexible configurations:
const routes = [
{
path: '/home',
name: 'home',
component: Home,
alias: '/welcome' // Alias configuration
},
{
path: '/legacy',
redirect: { name: 'home' } // Supports named route redirects
}
]
Integration with Composition API
Accessing route information in the setup
function:
import { useRoute, useRouter } from 'vue-router'
export default {
setup() {
const route = useRoute()
const router = useRouter()
// Access current route params
console.log(route.params.id)
// Programmatic navigation
function navigate() {
router.push({ name: 'user', params: { id: 123 } })
}
return { navigate }
}
}
Route Component Injections
Renamed route component injection properties:
$route
→useRoute()
$router
→useRouter()
- Removed the
next
callback inbeforeRouteEnter
, replaced with async/await
Enhanced TypeScript Support
Vue Router 4 has refactored its type system from the ground up, with major improvements including:
- Route configuration object type
RouteRecordRaw
- Extendable route meta field type
RouteMeta
- Navigation guard parameter type
NavigationGuard
- Route location object type
RouteLocationRaw
Removed Features
Some legacy features have been removed or replaced:
- Removed the
tag
prop in<router-link>
, replaced withv-slot
API - Removed the
append
prop, requiring manual path concatenation - Removed the
event
prop, navigation is now fully controlled byclick
events - Removed the
exact
matching mode, replaced with more flexibleactive-class
configurations
Performance Optimizations
Internal performance optimizations include:
- Refactored route matching algorithm for improved efficiency with large route tables
- Optimized navigation flow to reduce unnecessary component re-renders
- Switched to a more efficient path parser implementation
- Reduced memory usage and improved garbage collection efficiency
Migration Strategy Recommendations
Key steps for migrating from Vue Router 3 to 4:
- Update package reference to
vue-router@4
- Replace
new VueRouter()
withcreateRouter()
- Convert history mode to the new API format
- Update navigation guard implementations
- Adjust dynamic routing API calls
- Refactor type definitions (if using TypeScript)
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn