【问题标题】:VueJS - How to define routes for any number of optional parameters in Vue RouterVueJS - 如何在 Vue Router 中为任意数量的可选参数定义路由
【发布时间】:2019-06-17 22:38:01
【问题描述】:

我有包含类别、子类别和产品的树形导航。我需要为类别和产品定义两条路线。可以有多个嵌套的子类别。

我想展示相同的组件,例如/category/category/subcategory/subcategory/subcategory 也是如此。

产品路线看起来像category/product/productslugcategory/subcategory/subcategory/subcategory/product/productslug,其中product 是特定产品标签之前的前缀。

在 Laravel 中我做了这样的事情:

对于产品:

Route::get('/{category?}/product/{slug}', 'ProductController@getProductBySlug')->where('category', '.*');

对于类别:

Route::get('/{category?}', 'CategoryController@getCategoryBySlug')->where('category', '.*');

在 Vue 路由器中不能像这样工作:

routes: [
 {path: '/', component: HomeView},
 {path: '*/product/:slugproduct', component: ProductView},
 {path: '*', component: CategoryView},
]

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    我为您创建了一个codepen 来测试您的任务的正确解决方案。现在,让我解释一下它是如何工作的。 Vue-Router 有神奇的 reg-exp 模式,非常棒,更多信息on GitHub in path-to-regexp project

    只需将您的 * 更改为 (.*) 就可以了 - 就可以了。要从实际参数中获取模式组,您可以使用this.$route.params.pathMatch,它将包含当前的 reg-exp 组,路径中描述的其他命名参数将可用实际名称 - idslug 等。

    如您所见,我推送了一条自定义路由/category/subcategory/subcategory/product/100,控制台输出将如下所示:

    Vue mounted...
    Home component mounted...
    path: /category/subcategory/subcategory/product/100
    tree: /category/subcategory/subcategory
    id: 100
    

    如您所见,我们有 reg-exp (.*) 组和一个 id 参数。

    const Home = {
      data() {
        return { };
      },
      mounted() {
        console.log('Home component mounted...');
        console.log('path: ' + this.$route.path);
        console.log('tree: ' + this.$route.params.pathMatch);
        console.log('id: ' + this.$route.params.id);
      },
      template: `<div>Home component...</div>`
    };
    
    const router = new VueRouter({
      mode: 'hash',
      routes: [
        {
          path: '(.*)/product/:id',
          name: 'index',
          component: Home,
        }
      ]
    })
    
    const vm = new Vue({
      el: '#app',
      router,
      data: {},
      mounted() {
        console.log('Vue mounted...');
      }
    })
    
    router.push("/category/subcategory/subcategory/product/100");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.22/vue.min.js"></script>
    <div id="app">
      <router-view></router-view>
    </div>

    【讨论】:

      猜你喜欢
      • 2021-09-12
      • 1970-01-01
      • 2018-05-29
      • 2020-11-10
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 2021-05-17
      相关资源
      最近更新 更多