398 vue嵌套路由/子路由: children


導入 : url測試 parent 和child, 想讓child 在 parent 中顯示

  • parent 的內部 添加 : <router-view> </router-view>
  • 規則里添加 children
  • /child 和 child 的區別
    • 如果是/child => 直接訪問#/child就可以訪問 子組件
    • 如果是child => 訪問#/parent/child才可以訪問子組件

const parent = {
    template: `<p>parent  <router-view> </router-view> </p>`
}
const child = {
    template: `<p>child</p>`
} 

const router = new VueRouter({
    routes: [
        {
            path: '/parent',
            component: parent,
            children: [
                { path: '/child', component: child }
            ]
        }
    ]
})

07-嵌套路由.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>

<body>
    <div id="app">
        <!-- 1. 入口 -->
        <!-- 
            需求: child組件 放到 parent組件 里面
            辦法: children: [路由規則]
        -->

        <!-- 4. 出口 -->
        <router-view></router-view>
        <hr />
    </div>

    <script src="./vue.js"></script>
    <script src="./node_modules/vue-router/dist/vue-router.js"></script>
    <script>
        // 3. 組件
        const parent = {
            template: `<div> parent組件 -- <router-view></router-view> </div>`
        }

        const child = {
            template: `<div>child組件</div>`
        }

        //  實例化
        const router = new VueRouter({
            // 2. 規則
            routes: [{
                path: '/parent',
                component: parent,
                children: [{
                    // 子組件的path值前,加斜桿/,則瀏覽器的url中不需要寫成 /parent/child,直接寫/child即可。不加的話,就要寫成 /parent/child
                    path: '/child',
                    component: child
                }],
                // children: [{
                //     path: 'child',
                //     component: child
                // }]

                //  path : '/child'    => 哈希值 : /child
                //  path : 'child'     => 哈希值 : /parent/child
            }]
        })

        const vm = new Vue({
            router,
            el: '#app',
            data: {}
        })
    </script>
</body>

</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM