乐闻世界logo
搜索文章和话题

How does Nuxt.js routing system work and how is it different from Vue Router?

3月6日 23:12

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:

  1. Convention-based routing

    • Nuxt.js automatically scans the file structure under the pages directory and generates corresponding route configurations based on file paths
    • No need to manually configure a router.js file, reducing configuration complexity
  2. File naming rules

    • Basic routes: pages/index.vue corresponds to the / path
    • Nested routes: pages/user/profile.vue corresponds to the /user/profile path
    • Dynamic routes: Use underscore prefix, e.g., pages/user/_id.vue corresponds to /user/:id path
    • Nested dynamic routes: e.g., pages/user/_id/comments.vue corresponds to /user/:id/comments path
  3. Route parameter retrieval

    • Get route parameters in components via $route.params
    • Support for validating route parameters through the validate method
  4. Route navigation

    • Use <nuxt-link> component for declarative navigation
    • Use this.$router.push() for programmatic navigation

Key differences from Vue Router:

  1. Route generation method

    • Vue Router: Requires manual configuration of route rules
    • Nuxt.js: Automatically generates routes based on file system
  2. Route file structure

    • Vue Router: Usually concentrated in a single router.js file
    • Nuxt.js: Distributed in the file structure of the pages directory
  3. Layout system

    • Vue Router: Requires manual configuration of layout components
    • Nuxt.js: Built-in layout system managed through the layouts directory
  4. Middleware support

    • Vue Router: Uses route guards
    • Nuxt.js: Provides a more powerful middleware system supporting global, layout, and page-level middleware
  5. Preloading functionality

    • Nuxt.js provides route preloading functionality to improve user experience

Advanced routing features:

  1. Nested routes

    • Create directories with the same name as parent components and add _slug.vue etc. files inside
  2. Dynamic routes

    • Use _ prefix to create dynamic route parameters
    • Support parameter format validation through the validate method
  3. Route transition effects

    • Built-in support for page transition animations
  4. Route meta information

    • Set page title, description, and other meta information through the component's head method

Best practices:

  • Organize the pages directory 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
标签:Nuxt.js