[Vue]vue-router嵌套路由(子路由)
总共添加两个子路由,分别命名 Collection.vue(我的收藏)和 Trace.vue(我的足迹)
1、重构 router/index.js 的路由配置,需要使用 children 数组来定义子路由,具体如下:
import Vue from 'vue' import Router from 'vue-router' import Home from '@/Home' import Brand from '@/Brand' import Member from '@/Member' import Cart from '@/Cart' import Me from '@/Me'import Collection from '@/Collection'
import Trace from '@/Trace'
import Default from '@/Default'Vue.use(Router)
export default new Router({
// mode: 'history',
// base: __dirname,
// linkActiveClass: 'active', // 更改激活状态的 Class 值
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/brand',
name: 'Brand',
component: Brand
},
{
path: '/member',
name: 'Member',
component: Member
},
{
path: '/cart',
name: 'Cart',
component: Cart
},
{
path: '/me',
name: 'Me',
component: Me,
children: [
{
path: 'collection',// 以“/”开头的嵌套路径会被当作根路径,所以子路由上不用加“/”; 在生成路由时,主路由上的 path 会被自动添加到子路由之前,所以子路由上的 path 不用在重新声明主路由上的 path 了。
name: 'Collection',
component: Collection
},
{
path: 'trace',
name: 'Trace',
component: Trace
}
]
}
]
})
2、Me.vue 的代码如下:
<template> <div class="me"> <div class="tabs"> <ul> <!--<router-link :to="{name:'Default'}" tag="li" exact> 默认内容 </router-link>--> <router-link :to="{name:'Collection'}" tag="li" > 我的收藏 </router-link> <router-link :to="{name:'Trace'}" tag="li"> 我的足迹 </router-link> </ul> </div> <div class="content"> <router-view></router-view>//<router-link> 就是定义页面中点击的部分,<router-view> 定义显示部分,就是点击后,区配的内容显示在什么地方,会被匹配到的组件替换掉 </div> </div> </template> <script type="text/ecmascript-6"></script>
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
.me{
.tabs{
& > ul, & > ul > li {
margin: 0;
padding: 0;
list-style: none;
}
& > ul{
display: flex;
border-bottom: #cccccc solid 1px;
& > li{
flex: 1;
text-align: center;
padding: 10px;
&.router-link-active {
color: #D0021B;
}
}
}
}
}
</style>
3. 页面效果:
当访问到 http://localhost:8080/#/me 时,组件 Me 中 <router-view> 并没有渲染出任何东西,这是因为没有匹配到合适的子路由。如果需要渲染一些默认内容,需要在 children 中添加一个空的子路由:
{ path: '', name: 'Default', component: Default },
此时浏览器的效果:默认组件 Default 被渲染出来了: