vue-router 基本使用(三)——嵌套路由

嵌套路由,主要是由我們的頁面結構所決定的。當我們進入到home頁面的時候,它下面還有分類,如手機系列,平板系列,電腦系列。當我們點擊各個分類的時候,它還是需要路由到各個部分,如點擊手機,它肯定到對應到手機的部分。

  在路由的設計上,首先進入到 home ,然後才能進入到phone, tablet, computer.  Phone, tablet, compute 就相當於進入到了home的子元素。所以vue  提供了childrens 屬性,它也是一組路由,相當於我們所寫的routes。

  首先,在home頁面上定義三個router-link 標籤用於導航,然後再定義一個router-view標籤,用於渲染對應的組件。router-link 和router-view 標籤要一一對應。home.vue 組件修改如下:

<template>
    <div>
        <h1>home</h1><!-- router-link 的to屬性要注意,路由是先進入到home,然後才進入相應的子路由如 phone,所以書寫時要把 home 帶上 -->
        <p>
            <router-link to="/home/phone">手機</router-link>
            <router-link to="/home/tablet">平板</router-link>
            <router-link to="/home/computer">電腦</router-link>
        </p>
        <router-view></router-view>
    </div>
</template>

router.js 配置路由,修改如下:

const routes = [
    {
        path:"/home",     // 下面這個屬性也不少,因爲,我們是先進入home頁面,才能進入子路由
        component: home,     // 子路由
        children: [
            {
                path: "phone",
                component: phone
            },
            {
                path: "tablet",
                component: tablet
            },
            {
                path: "computer",
                component: computer
            }
        ]
    },
    {
        path: "/about",
        component: about
    },
    {
        path: "/user/:id",
        component: user
    },
    {
        path: '/', 
        redirect: '/home' 
    }
]

這時當我們點擊home 時,它下面出現手機等字樣,但沒有任何對應的組件進行顯示,這通常不是我們想要的。要想點擊home時,要想渲染相對應的子組件,那還需要配置一條路由。當進入到home 時,它在children中對應的路由path 是空 ‘’,完整的childrens 如下:

children: [
    {
        path: "phone",
        component: phone
    },
    {
        path: "tablet",
        component: tablet
    },
    {
        path: "computer",
        component: computer
    },    // 當進入到home時,下面的組件顯示
    {
        path: "",
        component: phone
    }
]

效果:

源碼地址:https://github.com/wanghongzheng/my_vue/tree/dev

轉發鏈接:https://www.cnblogs.com/SamWeb/p/6610733.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章