在 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