vue-router的嵌套路由


一、前言

嵌套路由是一个很常见的功能

  • 比如在home页面中, 我们希望通过/home/news和/home/message访问一些内容.
  • 一个路径映射一个组件, 访问这两个路径也会分别渲染两个组件.
    在这里插入图片描述

二、使用步骤

实现嵌套路由有两个步骤:

  • 创建对应的子组件, 并且在路由映射中配置对应的子路由
  • 组件内部使用<router-view>标签

1、创建两个子路由对应的组件
在这里插入图片描述

2、要在嵌套的出口中渲染组件,需要在 VueRouter 的参数中使用 children 配置

children 配置就像 routes 配置一样,是一个数组,所以也可以嵌套多层路由。

注意:/ 开头的嵌套路径会被当作根路径,所以子路由上不用加 / 。在生成路由时,主路由上的path会被自动添加到子路由之前,所以子路由上的path不用在重新声明主路由上的path了。

//配置路由的信息
import Vue from 'vue'
import Router from 'vue-router'

//路由懒加载
const Home = () => import('../components/Home')
const HomeMessage = () => import('../components/HomeMessage')
const HomeNews = () => import('../components/HomeNews')

Vue.use(Router)

const routes = [
  {
    path:'',
    redirect:'/home'
  },
  {
    path: '/home',
    component: Home,
    children:[
      {
        path:'news', //嵌套路由的时候,路径前边不能加 /
        component:HomeNews
      },
      {
        path:'message',
        component: HomeMessage
      }
    ]
  }
]

const router = new Router({
  routes
});

export default router

3、在Home组件中使用

//Home.vue文件
<template>
  <div>
    <h2 class="title">我是首页Home</h2>
    //注意这里的路径必须是完整的
    <router-link to="/home/news">新闻</router-link>
    <router-link to="/home/message">消息</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
  export default {
    name: "Home"
  }
</script>

<style scoped>

</style>

此时,基于上面的配置,当你访问 /home 时,router-view是不会渲染任何东西,这是因为没有匹配到合适的子路由。如果你想要渲染点什么,可以提供一个 空的子路由

const router = new VueRouter({
  routes: [
    {
      path: '/home', 
      component: Home,
      children: [
        // 当 /home 匹配成功,
        // HomeNews会被渲染在 Home的 <router-view> 中
        // { path:'', redirect:'news'},使用重定向
        { path: '', component: HomeNews},

        // ...其他子路由
      ]
    }
  ]
})

三、资料

嵌套路由 | Vue Router官网

前端学习交流QQ群,群内学习讨论的氛围很好,大佬云集,期待您的加入:862748629 点击加入

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值