【问题标题】:How to achieve n levels of nested dynamic routes in Vue.js?Vue.js中如何实现n级嵌套动态路由?
【发布时间】:2019-08-24 13:17:01
【问题描述】:

我想在 Vue.js 中实现 n 级动态嵌套路由,其中​​ n 对我来说是未知的。 例如 -

abc.com/ctx-path/component/1/2/...../n

其中 1,2,...n 是级别

如何使用 Vue-router 实现这一点?

【问题讨论】:

    标签: vue.js routing vue-router nested-routes dynamic-routing


    【解决方案1】:

    vue-router 路径匹配在幕后使用path-to-regexp。 所以应该可以这样写

    { path: '/ctx-path/component/:id+', component: Component }
    

    { path: '/ctx-path/component/:id*', component: Component }
    

    您也可以在run time 处动态添加路径,但您需要有一个触发器才能添加它。

    最后一个选择是使用catch all route 并添加您自己的逻辑。

    【讨论】:

    • 您的建议是使用通配符进行正则表达式匹配。但我想要的是为不同的路线打开不同的页面。例如:路径:'/ctx-path/component/1/2/..../id1/.....n' & 路径:'/ctx-path/component/1/2/.... /id2/.....n' 应该打开 2 个不同的页面。
    • @Radu Diță 也许你可以帮帮我。看看这个:stackoverflow.com/questions/57836601/…
    【解决方案2】:

    这是来自文档:

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

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

    【讨论】:

    • 问题是如果此示例中的 也是动态的。
    【解决方案3】:

    双重动态嵌套路由通过嵌套 URL 参数过滤单个视图

    const routes = [
      {
        path: '/category/:categoryId',
        name: 'category',
        component: () =>
          import(/* webpackChunkName: "product" */ '../views/Categories.vue'),
        props: (route: Route) => ({
          categoryId: route.params.categoryId,
        }),
      },
      {
        path: '/category/:categoryId/:attributeIdsJsonString',
        name: 'attributeFilter',
        component: () =>
          import(/* webpackChunkName: "product" */ '../views/Categories.vue'),
        props: (route: Route) => ({
          categoryId: route.params.categoryId,
          attributeIdsJsonString: route.params.attributeIdsJsonString,
        }),
      },
    ];
    
    const router = new VueRouter({
      routes,
    });
    

    像这样使用不同的路由名称意味着beforeRouteUpdate 在某些情况下不会触发,所以也使用beforeRouteEnter

    【讨论】:

      猜你喜欢
      • 2018-05-29
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      相关资源
      最近更新 更多