一级路由和二级路由的定义
一级路由
一级路由是网站的主要页面导航。在VueRouter中,可以通过以下方式定义一级路由:
const routes = [
{
path: '/',
component: Home, // 使用Home组件作为根路径的组件
name: 'Home',
},
{
path: '/about',
component: About, // 使用About组件作为/about路径的组件
name: 'About',
},
// 其他一级路由...
];
在上述示例中定义了两个一级路由:根路径(‘/’)和’/about’。每个路由都有一个与之关联的组件,例如Home和About。这些组件将在用户访问相应路由时呈现。
二级路由
二级路由是一级路由下的子页面或嵌套页面。要在VueRouter中定义二级路由,可以在一级路由的组件中添加<router-view>
来为二级路由留出位置:
<template>
<div>
<h1>About Us</h1>
<router-view></router-view> <!-- 这里是二级路由的出口 -->
</div>
</template>
在’/about’路由下定义二级路由,如’/about/team’和’/about/contact’等。
具体路由出口的定义
要在组件中定义具体路由出口,首先在组件中使用<router-view>
。在路由配置中为每个二级路由指定组件:
const routes = [
// 一级路由...
{
path: '/about',
component: About,
children: [
{
path: '', // 默认二级路由,访问/about时显示这个
component: AboutMain,
name: 'AboutMain',
},
{
path: 'team', // /about/team
component: AboutTeam,
name: 'AboutTeam',
},
{
path: 'contact', // /about/contact
component: AboutContact,
name: 'AboutContact',
},
],
},
// 其他一级路由...
];
在上述示例中,‘/about’路由下有三个二级路由:默认路由(空路径)、’/about/team’和’/about/contact’。每个二级路由都与一个具体的组件相关联,例如AboutMain、AboutTeam和AboutContact。
在About组件的模板中,只需添加<router-view>
元素,VueRouter会根据用户访问的子路由自动渲染相应的组件。