[Vue]vue-router嵌套路由(子路由)

總共添加兩個子路由,分別命名Collection.vue(個人收藏)和Trace.vue(個人足跡)vue

一、重構router/index.js的路由配置,須要使用children數組來定義子路由,具體以下:vue-router

 

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 } ] } ] })

 

二、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中添加一個空的子路由:less

{ path: '', name: 'Default', component: Default },

此時瀏覽器的效果:默認組件Default被渲染出來了:ecmascript

 

轉自:http://www.javashuo.com/article/p-wqiirwwx-mt.htmlflex

相關文章
相關標籤/搜索