Nuxt中的动态嵌套路由

时间:2020-04-27 18:24:27

标签: vue.js nuxt.js vue-router

我必须处理Nuxt中的静态路由和动态路由。

但是,我正在尝试确定是否可以有效地使用无限的嵌套页面。

例如,在诸如WordPress的标准CMS中,我可以定义一个深层的页面,例如:

*hostname.com/page/other-page/another/yet-another/one-more/final-page*

我想我可以定义不必要的深度页面结构,例如:

- /_level1
   - index.vue
   /_level2
      - index.vue
      / _level3
         - index.vue
         /level4
            -index.vue

...等等。但这并不是特别有效或可扩展的感觉,并且会引入很多重复的代码和维护问题。

有没有更好的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以将嵌套路由与“子级”选项一起使用。

https://router.vuejs.org/guide/essentials/nested-routes.html

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // UserProfile will be rendered inside User's <router-view>
          // when /user/:id/profile is matched
          path: 'profile',
          component: UserProfile
        },
        {
          // UserPosts will be rendered inside User's <router-view>
          // when /user/:id/posts is matched
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})

您还可以从单独的文件导入子路由。

import UserRoutes from "./users/router.js"


const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: UserRoutes
    }
  ]
})

然后在您的users / router.js中:

export default [
  {
    // UserProfile will be rendered inside User's <router-view>
    // when /user/:id/profile is matched
    path: 'profile',
    component: UserProfile
  },
  {
    // UserPosts will be rendered inside User's <router-view>
    // when /user/:id/posts is matched
    path: 'posts',
    component: UserPosts
  }
]