vue-router嵌套路由详解

来源:互联网 发布:淘宝返利软件哪个好用 编辑:程序博客网 时间:2024/06/10 02:46

嵌套路由顾名思义就是路由的多层嵌套。

结合vue-router仿天猫底部导航栏,给组件Me添加嵌套路由,也叫子路由。

总共添加两个子路由,分别命名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',          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: '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>    </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>并没有渲染出任何东西,这是因为没有匹配到合适的子路由。如果需要渲染一些默认内容,需要在children中添加一个空的子路由:

{      path: '',      name: 'Default',      component: Default},
此时浏览器的效果:默认组件Default被渲染出来了


可以看出不同组件之间用到了相同的class类名,并且设置样式时之间会互相影响,所有我们需要在组件内的style标签上添加scoped属性

<style lang="less" rel="stylesheet/less" type="text/less" scoped>

本文参考 技术胖博客  vue-router官网