Vue 嵌套路由

165 阅读1分钟

文章目录

嵌套路由

说白了就是选项卡中又嵌套一个选项卡。

可以看看官方的例子 传送门

具体实现

接着路由管理的代码 路由管理

我们继续在pages 文件夹下新建两个路由组件 用来嵌套。

chilrenRoute1.vue

<template>
<div>
  chilrenRoute1
</div>
</template>

<script>
  export default {
  }
</script>

<style scoped>
div{
  color: greenyellow;
}
</style>

chilrenRoute2.vue

<template>
<div>
  chilrenRoute2
</div>
</template>

<script>
  export default {
  }
</script>

<style scoped>
div{
  color: green;
}
</style>

然后在路由管理js中管理路由

我们需要将这两个路由添加到about 路由下面

这里就需要用到chilren属性来配置了

在这里插入图片描述
代码


/**
 路由器模块
 **/

//引入Vue 和 路由插件
import Vue from 'vue'
import VueRouter from 'vue-router'



//引入路由组件
import About from '../pages/About'
import Home from '../pages/Home'

import chilrenRoute1 from '../pages/chilrenRoute1'
import chilrenRoute2 from '../pages/chilrenRoute2'

//调用路由器
Vue.use(VueRouter)

//向外暴露路由器对象
export default new VueRouter({
//n个路由
  //routes 不是  routers 切记  不然    <router-view> </router-view> 内容不显示 无法跳转到路径对应的路由界面中
  routes:[
  {
    path:"/about",
    component:About,
    //子路由  / 代表的是根路径  子路由url要么写全路径 要么 直接写子路由路径不要加 /
    children:[
      {
        path:"chilrenRoute1",
        component:chilrenRoute1
      },
      {
        path:"/about/chilrenRoute2",
        component:chilrenRoute2
      }
    ]
  },
  {
    path:"/home",
    component:Home
  },
  //默认请求
  {
    //根路径
    path:'/',
    redirect:'/about'
  }
]

})

然后在About 路由组件中使用子路由,也就是嵌套路由


<template>
<div>
  about ..............................
  <router-link to="/about/chilrenRoute1"> chilrenRoute1 </router-link>
  <router-link to="/about/chilrenRoute2"> chilrenRoute2 </router-link>

  <router-view></router-view>
</div>

</template>

<script>
  export default {
  }
</script>

<style>
</style>

页面效果

在这里插入图片描述

点击 chilrenRoute1
在这里插入图片描述

点击chilrenRoute2

在这里插入图片描述