VueJS - 如何在 Vue 路由器中为任意数量的可选参数定义路由



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

我想显示相同的组件,例如 /category/category/subcategory/subcategory/subcategory

产品路由看起来像category/product/productslugcategory/subcategory/subcategory/subcategory/product/productslug其中product是特定产品 slug 之前的前缀。

在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-Router 具有神奇的正则表达式模式,可以很棒,更多信息在 GitHub 的路径到正则表达式项目中。

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

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

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

如您所见,我们按预期(.*)组进行了正则表达式和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>

最新更新