vue.js - Nuxt 中的动态嵌套路由

标签 vue.js nuxt.js vue-router

我必须掌握 Nuxt 中的静态路由和动态路由。

但是,我正在尝试弄清楚是否可以拥有有效无限的嵌套页面。

例如,在标准 CMS(例如 Wordpress)中,我可以定义深层页面嵌套,例如:

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

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

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

...等等。但这感觉不是特别高效或可扩展,并且引入了大量重复代码和维护问题。

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

最佳答案

您可以使用带有“子级”选项的嵌套路由。

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
  }
]

关于vue.js - Nuxt 中的动态嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61465779/

相关文章:

javascript - nuxt js 中的 asyncData 和方法有什么不同?

javascript - nuxt 应用程序的 vue-social-sharing 中的 Vuetify 按钮

vue.js - Nuxt 中的 Stylelint 错误(基于类): Unexpected empty source (no-empty-source)

javascript - vue-google-map 将信息窗口设置在标记上方

typescript - 在 typescript 中增强 vue.js

javascript - 在 VueJS 的 v-for 循环中输出数据属性上的数学函数结果的正确方法是什么?

javascript - 高级 Vue 路由器守卫

javascript - Vuejs路由刷新时重定向

vue.js - VueRouter 和元字段

javascript - Vuex getter 返回未定义的值