1、重構(gòu)router/index.js的路由配置,需要使用children數(shù)組來定義子路由,具體如下:
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', // 更改激活狀態(tài)的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',
name: 'Collection',
component: Collection
},
{
path: 'trace',
name: 'Trace',
component: Trace
}
]
}
]
})
以“/”開頭的嵌套路徑會被當作根路徑,所以子路由上不用加“/”;
在生成路由時,主路由上的path會被自動添加到子路由之前,所以子路由上的path不用在重新聲明主路由上的path了。
2、Me.vue的代碼如下:
<template>
<div class="me">
<div class="tabs">
<ul>
<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>
</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>
頁面效果:
當訪問到http://localhost:8080/#/me時,組件Me中<router-view>并沒有渲染出任何東西,這是因為沒有匹配到合適的子路由。如果需要渲染一些默認內(nèi)容,需要在children中添加一個空的子路由:
{
path: '',
name: 'Default',
component: Default
},
此時瀏覽器的效果:默認組件Default被渲染出來了
可以看出不同組件之間用到了相同的class類名,并且設置樣式時之間會互相影響,所有我們需要在組件內(nèi)的style標簽上添加scoped屬性
<style lang="less" rel="stylesheet/less" type="text/less" scoped>