六、Vue Router 嵌套路由

嵌套路由

在入口模板中设置的<router-view>是最顶层的出口。子组件中可以嵌套<router-view>为子路由匹配的出口。

const User = {
    template: `
        <div class="user">
            <h2>User {{ $route.params.id }}</h2>
            <router-view></router-view>
        </div>
    `
}

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

<script>
    const router = new VueRouter({
        routes: [
            {
                path: '/user/:id',
                component: User,
                // 自路由配置
                children: [
                    // 当 /user/:id/profile 匹配成功
                    // 则会在子路由出口中渲染 UserProfile 组件
                    { path: 'profile', component: UserProfile }
                ]
            }
        ] 
    });
</script>

注意: 在子路由中 /开头的嵌套路径会被当作根路径。如果你要实现/user/123,在子路由配置路径时就不能带有/。如果有/,则匹配为 /123

在子路由中,必须提供一个空路径的子路由。这样当你匹配父路由的路径时,空的子路由组件会被渲染,否则不会

猜你喜欢

转载自www.cnblogs.com/yuxi2018/p/11967270.html