欢迎阅读 Vue.js Router 的官方文档!以下是关于路由管理的核心内容,帮助你快速上手并深入理解其功能。


🧩 基础用法

  1. 安装与引入

    npm install vue-router
    

    main.js 中注册:

    import { createRouter, createWebHistory } from 'vue-router'
    const router = createRouter({
      history: createWebHistory(),
      routes: [
        // 路由配置示例
      ]
    })
    
  2. 创建路由实例

    • 使用 createWebHistory() 配置历史模式
    • 通过 routes 数组定义路径与组件映射关系
Vue Router 基础用法示意图

📜 路由配置详解

  • 静态路由

    {
      path: '/about',
      component: AboutComponent
    }
    
  • 动态路由
    通过 :param 匹配动态段:

    {
      path: '/user/:id',
      component: UserComponent
    }
    
  • 嵌套路由
    配置子路由:

    {
      path: '/dashboard',
      component: DashboardLayout,
      children: [
        { path: 'profile', component: ProfileComponent }
      ]
    }
    
路由配置结构图

🔄 编程式导航

使用 this.$router.push() 实现跳转:

this.$router.push({ path: '/community' })
  • 支持参数传递:

    this.$router.push({ name: 'user', params: { id: 123 } })
    
  • 替换当前历史记录:

    this.$router.replace({ path: '/login' })
    
编程式导航方法示意图

📌 常见问题与解决方案

  • 404 页面
    配置通配符路由:

    {
      path: '/:catchAll(.*)',
      component: NotFoundComponent
    }
    
  • 路由懒加载
    使用动态导入:

    const Foo = () => import('./views/Foo.vue')
    
  • 命名路由
    为路由指定 name 属性:

    {
      path: '/profile',
      name: 'profile',
      component: ProfileComponent
    }
    
  • 导航守卫
    全局守卫示例:

    router.beforeEach((to, from, next) => {
      // 验证权限逻辑
      next()
    })
    
路由调试与优化建议

📚 扩展阅读

是否需要进一步了解 Vue Router 的 API 文档或实际案例?欢迎随时探索本站其他资源!🌱