aspirinemaga
aspirinemaga

Reputation: 3937

Make two types of route params in Vue.js to work

I would like to have URL in nested sets of categories following by a product. Not sure how to make a route matching correctly.

URLs I would like to have:

--- renders a "category.show.vue": /$categorySlug+
app.com/catA/catB/
app.com/catA/catB/catXXX

--- renders a "product.show.vue": /$categorySlug+/$id-$productSlug
app.com/catA/111-nvidia-rtx-3080ti
app.com/catA/catB/222-nvidia-rtx-2060
app.com/catC/catD/333-iphone-13-pro

I tried this but it's gives me the errors:

{
  path: '/:slug(\\w+)+/:productSlug(\\d+)',
  name: 'product.show',
  props: route => ({ slug: route.params.slug }),
  component: () => import('pages/product.show.vue')
},
{
  path: '/:slug+',
  name: 'category.show',
  props: route => ({ slug: route.params.slug }),
  component: () => import('pages/category.show.vue')
}

Is there a way to make it work together ?

Upvotes: 0

Views: 119

Answers (1)

tony19
tony19

Reputation: 138326

The regex pattern in :productSlug(\\d+) (i.e., \d+) matches only digits, but your product URLs actually contain more than just digits (e.g., one of them ends with /111-nvidia-rtx-3080ti), so no match occurs. The param's pattern must match exactly.

To resolve the issue, add a wildcard matcher to the productSlug pattern:

// BEFORE
// :productSlug(\\d+)

// AFTER
:productSlug(\\d+.+)
                 ^^ one or more characters, matching anything

Also, it looks like there is only one product in each URL, so the pattern for the route param should not be appended with +:

// BEFORE
// :productSlug(⋯)+

// AFTER
:productSlug(⋯)

The final route path for product.show should be:

path: '/:slug(\\w+)+/:productSlug(\\d+.+)',

demo

Upvotes: 1

Related Questions