Vue的路由模式以及多级路由的使用

在 Vue.js 中,路由是管理应用页面和组件的关键部分。Vue Router 是 Vue.js 的官方路由管理器,支持多种路由模式和多级路由。下面将详细解释 Vue Router 的路由模式以及如何使用多级路由。

1. Vue Router 路由模式

Vue Router 主要有两种路由模式:

1.1 Hash 模式
  • 默认的路由模式。
  • URL 中包含 # 符号,后面的部分是路由的路径。
  • 例如:http://localhost:8080/#/home
  • 优点:
    • 不需要服务器配置,直接通过 URL 哈希来实现路由。
    • 兼容性好,支持旧版浏览器。
  • 使用示例:
    const router = new VueRouter({
        mode: 'hash',
        routes: [
            { path: '/home', component: Home },
            { path: '/about', component: About }
        ]
    });
    
1.2 History 模式
  • 使用 HTML5 的 History API 来实现路由。
  • URL 中不包含 # 符号,路径看起来更加干净。
  • 例如:http://localhost:8080/home
  • 优点:
    • URL 结构更美观,符合 SEO 优化要求。
  • 缺点:
    • 需要服务器配置支持,以确保所有路由都能返回 index.html,从而使 Vue Router 能够接管路由。
  • 使用示例:
    const router = new VueRouter({
        mode: 'history',
        routes: [
            { path: '/home', component: Home },
            { path: '/about', component: About }
        ]
    });
    

2. 多级路由

多级路由允许你在一个路由下嵌套多个子路由。通常在复杂的应用中使用,可以创建更加结构化的路由。

2.1 设置多级路由

下面是一个使用 Vue Router 设置多级路由的示例:

// 导入组件
import Vue from 'vue';
import Router from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';
import User from './components/User.vue';
import UserProfile from './components/UserProfile.vue';
import UserPosts from './components/UserPosts.vue';
Vue.use(Router);
// 创建路由实例
const router = new Router({
    mode: 'history', // 使用 history 模式
    routes: [
        {
            path: '/home',
            component: Home
        },
        {
            path: '/about',
            component: About
        },
        {
            path: '/user',
            component: User,
            children: [
                {
                    path: 'profile', // /user/profile
                    component: UserProfile
                },
                {
                    path: 'posts', // /user/posts
                    component: UserPosts
                }
            ]
        }
    ]
});
export default router;
2.2 组件结构

对于上述路由配置,组件的结构可能是这样的:

<!-- User.vue -->
<template>
  <div>
    <h2>User Page</h2>
    <router-link to="profile">Profile</router-link>
    <router-link to="posts">Posts</router-link>
    <router-view></router-view> <!-- 显示子路由 -->
  </div>
</template>
<script>
export default {
  name: 'User'
}
</script>
<!-- UserProfile.vue -->
<template>
  <div>
    <h3>User Profile</h3>
    <!-- 用户资料内容 -->
  </div>
</template>
<script>
export default {
  name: 'UserProfile'
}
</script>
<!-- UserPosts.vue -->
<template>
  <div>
    <h3>User Posts</h3>
    <!-- 用户帖子内容 -->
  </div>
</template>
<script>
export default
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值