App.vue
因为二级路由在一级路由里,所以子组件组件都放在home文件里,即是src/pages/home文件夹中创建二级导航的组件classic.vue和Hot.vue
const routes = [
{
path: "/",
redirect: "/home_1",
},
{
path: "/home_1",
component: () =>
import(/*webpackChunkName:"home"*/ "../pages/home/index.vue"),
name: "home",
alias: "/family",
-----------------------------------------------------------------------------------------
// 子路由重定向
redirect:'/home_1/f-hot', // 不是写在子路由中!!!!
// 用于实现子路由表
children: [
{
path: "f-hot", // 子路由的path不用加/ 会自动加
component: () =>
import(/*webpackChunkName:home*/ "../pages/home/Hot.vue"),
name:'f-hot_1'
},
{
path: "classic", // 子路由的path不用加/ 会自动加
component: () =>
import(/*webpackChunkName:home*/ "../pages/home/classic.vue"),
name:'classic_1'
},
],
},
-----------------------------------------------------------------------------------------
{
path: "/about",
component: () =>
import(/*webpackChunkName:'about'*/ "../pages/about/index.vue"),
name: "about",
},
scr/pages/home/index.vue
<template>
<div>
home组件
<hr />
<!-- 导航区域 -->
<ul class="home-nav-list">
<li>
<router-link active-class="active" to="/home_1/f-hot">热映</router-link>
</li>
<li>
<router-link active-class="active" to="/home_1/classic">经典电影</router-link>
</li>
</ul>
<!-- 子路由展示区 -->
<div>
<router-view></router-view>
</div>
</div>
</template>
<style lang="stylus" scoped>
.home-nav-list
display flex
width 200px
justify-content space-evenly
.active
background blue
color white
</style>
命名路由
除了 path
以外,你还可以为任何路由提供 name
。这有以下优点:
- 没有硬编码的URL
params
的自动编码/解码- 防止你在url中出现打字错误
- 绕过路径排序(如显示一个)
我们将上面的案例进行优化
children: [
{
path: "f-hot",
component: () =>
import(/*webpackChunkName:home*/ "../pages/home/Hot.vue"),
name:'f-hot_1' // 添加name属性
},
{
path: "classic",
component: () =>
import(/*webpackChunkName:home*/ "../pages/home/classic.vue"),
name:'classic_1' // 添加name属性
},
],
要链接到一个命名的路由,可以向 router-link
组件的 to
属性传递一个对象
<!-- :to={name:'命名路由的名字'} -->
<router-link :to="{name:'f-hot_1'}">热映</router-link>
<router-link :to="{name:'classic_1'}">经典电影</router-link>