Vue.js 路由管理

学习Vue Router的使用和最佳实践

1. Vue Router 简介

Vue Router是Vue.js的官方路由管理器,它与Vue.js核心深度集成,让构建单页面应用变得简单。


// 创建路由实例
const router = VueRouter.createRouter({
    history: VueRouter.createWebHistory(),
    routes: [
        { path: '/', component: Home },
        { path: '/about', component: About }
    ]
})

// 使用路由
const app = Vue.createApp({})
app.use(router)
app.mount('#app')
                    

2. 基本路由配置

学习如何配置基本的路由规则和导航。

路由示例


const routes = [
    {
        path: '/',
        component: {
            template: '<div>首页内容</div>'
        }
    },
    {
        path: '/about',
        component: {
            template: '<div>关于页面</div>'
        }
    },
    {
        path: '/user/:id',
        component: {
            template: '<div>用户ID: {{ $route.params.id }}</div>'
        }
    }
]
                    

3. 路由参数

学习如何在路由中传递和获取参数。

路由参数示例


const User = {
    template: `
        <div>
            <h2>用户详情</h2>
            <p>用户ID: {{ $route.params.id }}</p>
            <button @click="goBack">返回</button>
        </div>
    `,
    methods: {
        goBack() {
            this.$router.back()
        }
    }
}
                    

4. 嵌套路由

学习如何创建嵌套的路由结构。

嵌套路由示例


const routes = [
    {
        path: '/user',
        component: User,
        children: [
            {
                path: 'profile',
                component: UserProfile
            },
            {
                path: 'posts',
                component: UserPosts
            }
        ]
    }
]
                    

5. 导航守卫

学习如何使用导航守卫控制路由访问。

导航守卫示例


router.beforeEach((to, from, next) => {
    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login')
    } else {
        next()
    }
})
                    

6. 路由懒加载

学习如何实现路由组件的懒加载,提高应用性能。


const routes = [
    {
        path: '/about',
        component: () => import('./views/About.vue')
    }
]
                    

7. 综合示例:博客系统

下面是一个使用Vue Router构建的简单博客系统示例。

路由最佳实践

  • 使用命名路由,便于维护和重构
  • 合理使用路由懒加载,优化性能
  • 使用导航守卫处理权限控制
  • 保持路由配置的清晰和模块化

练习

尝试创建一个简单的电商网站路由系统,包含以下功能:

  • 商品列表页面
  • 商品详情页面
  • 购物车页面
  • 用户中心页面
  • 订单管理页面