Nuxt.js has a built-in file system-based routing system that encapsulates and extends Vue Router, providing a more concise way to define routes.
How the routing system works:
-
Convention-based routing
- Nuxt.js automatically scans the file structure under the
pagesdirectory and generates corresponding route configurations based on file paths - No need to manually configure a
router.jsfile, reducing configuration complexity
- Nuxt.js automatically scans the file structure under the
-
File naming rules
- Basic routes:
pages/index.vuecorresponds to the/path - Nested routes:
pages/user/profile.vuecorresponds to the/user/profilepath - Dynamic routes: Use underscore prefix, e.g.,
pages/user/_id.vuecorresponds to/user/:idpath - Nested dynamic routes: e.g.,
pages/user/_id/comments.vuecorresponds to/user/:id/commentspath
- Basic routes:
-
Route parameter retrieval
- Get route parameters in components via
$route.params - Support for validating route parameters through the
validatemethod
- Get route parameters in components via
-
Route navigation
- Use
<nuxt-link>component for declarative navigation - Use
this.$router.push()for programmatic navigation
- Use
Key differences from Vue Router:
-
Route generation method
- Vue Router: Requires manual configuration of route rules
- Nuxt.js: Automatically generates routes based on file system
-
Route file structure
- Vue Router: Usually concentrated in a single
router.jsfile - Nuxt.js: Distributed in the file structure of the
pagesdirectory
- Vue Router: Usually concentrated in a single
-
Layout system
- Vue Router: Requires manual configuration of layout components
- Nuxt.js: Built-in layout system managed through the
layoutsdirectory
-
Middleware support
- Vue Router: Uses route guards
- Nuxt.js: Provides a more powerful middleware system supporting global, layout, and page-level middleware
-
Preloading functionality
- Nuxt.js provides route preloading functionality to improve user experience
Advanced routing features:
-
Nested routes
- Create directories with the same name as parent components and add
_slug.vueetc. files inside
- Create directories with the same name as parent components and add
-
Dynamic routes
- Use
_prefix to create dynamic route parameters - Support parameter format validation through the
validatemethod
- Use
-
Route transition effects
- Built-in support for page transition animations
-
Route meta information
- Set page title, description, and other meta information through the component's
headmethod
- Set page title, description, and other meta information through the component's
Best practices:
- Organize the
pagesdirectory structure rationally to keep routing logic clear - Add parameter validation when using dynamic routes
- Use middleware to handle common logic such as permission validation
- Use layout components appropriately to reduce code duplication