Vue中的路由嵌套

路由嵌套,即在当前路由中注册子路由中,形成父子结构,显示子路由对应的组件,需要网址在父路由的pathname下才能实现,后面再具体演示。子路由内也可以注册它的子路由,一直下去就可以形成一个庞大的“家族”。

简单来说,就是在一个路由的页面下,继续使用路由加载新的组件;可以将嵌套路由理解为父子路由,常见的多导航界面通常就是由多层嵌套的组件组合而成。

嵌套路由还有一个优点,就是让新的页面内容展示在父组件的占位符(即router-view标签)中,这样有利于页面结构的搭建,结构清晰。

如何注册子路由呢?

需要用到一个children属性,其值为数组,数组中的每一项对应一个子路由。

代码演示就明白了:以home路由为例,为它创建三个子路由

 {
        path:"/home",
        name:"home",
        component:()=>import('../views/home/index.vue'),
        children:[
            {
                path:"/home/home1",
                name:"home1",
                component:()=>import('../views/home/home1/index.vue')
            },
            {
                path:"/home/home2",
                name:"home2",
                component:()=>import('../views/home/home2/index.vue')
            },
            {
                path:"/home/home3",
                name:"home3",
                component:()=>import('../views/home/home3/index.vue')
            },
        ]
    }

这个时候子路由已经注册好了,子路由的path路径都是在父路由的基础下创建,我们再在对应引入组件的位置创建好组件。

结构:

 最后一步,如果要想在页面渲染出来我们还需要在home路由对应的组件中添加router-view标签。

<template>
    <div class="box3">
        <h1>home</h1>
        <!-- 方法一 -->
        <router-link to="/login/ss">通过router-link标签转跳</router-link>
        <!-- 方法二 -->
        <button @click="rto">通过$router.push转跳</button>

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

这个时候,我们在地址栏输入子路由的网址就可以显示出来了。

效果:

我们还可以做一个优化,在home路由对应的组件加载到页面时,我们需要默认加载一个子路由时,我们需要做一个重定向,在home路由中redirect:"重定向的子路由网址"。这个时候加载home页面时默认会加一个子路由。

代码:默认显示home2

 {
        path:"/home",
        name:"home",
        component:()=>import('../views/home/index.vue'),
        redirect:"/home/home2",//当网址为/home时重定向到/home/home2
        children:[
            {
                path:"/home/home1",
                name:"home1",
                component:()=>import('../views/home/home1/index.vue')
            },
            {
                path:"/home/home2",
                name:"home2",
                component:()=>import('../views/home/home2/index.vue')
            },
            {
                path:"/home/home3",
                name:"home3",
                component:()=>import('../views/home/home3/index.vue')
            },
        ]
    }

页面:当我们网址为localhost:8080/home时自动转跳到localhost:8080/home/home2,这时子路由home2对应的组件加载到home中。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值