[Vuejs]-Vue-router: define pretty URL for filter page with pagination

0👍

You will have to create multiple routes for this to work.

If you are trying to achieve it with just one route, there are some problems with the schema.

  1. example.com/shop/ might be followed by either pagination or filter.
  2. The filters may contain 1 or more items.
  3. Pagination might also be followed by a sort.
  4. Could a filter be followed by a sort in the absence of pagination?

So the single path that can handle all the above is something like

{
  path: '/shop/filters/:filter*/page/:number?/sort/:order?',
  component: resolve(__dirname, 'pages/shop.vue')
}

This does the following,

  1. All parameters are optional.
  2. Filters can contain 0 or more item.

But the URL might trip you off.

# Ideal path with more than one filter, pagination, and sort
/shop/filters/color-green/size-big/page/2/sort/ASC

# Single filter, pagination, and sort
/shop/filters/size-big/page/2/sort/ASC

# No filters, but with pagination and sort
/shop/filters/page/2/sort/ASC

# No filter or pagination, but has sort
/shop/filters/page/sort/ASC

# No filter, pagination or sort (default page)
/shop/filters/page/sort

# No Sort
/shop/filters/color-green/size-big/page/2/sort

# no pagination
/shop/filters/color-green/size-big/page/sort/2

# no sort or pagination
/shop/filters/color-green/size-big/page/sort

But this is clearly not what you want. So instead, create multiple routes.

[{
  path: '/shop/',
  component: resolve(__dirname, 'pages/shop.vue')
},{
  path: '/shop/filters/:filter*/page/:number/sort/:order',
  component: resolve(__dirname, 'pages/shop.vue')
},{
  path: '/shop/filters/:filter*/page/:number',
  component: resolve(__dirname, 'pages/shop.vue')
},{
  path: '/shop/filters/:filter*',
  component: resolve(__dirname, 'pages/shop.vue')
},{
  path: '/shop/page/:number/sort:order',
  component: resolve(__dirname, 'pages/shop.vue')
},{
  path: '/shop/page/:number',
  component: resolve(__dirname, 'pages/shop.vue')
},]

I might have missed something or the order might not be accurate, but I guess you got the gist of what you need to do.

Since vue-router uses path-to-regexp, you can test it on forbeslindesay.github.io/express-route-tester

Leave a comment