Nuxt Capture All/Unknown Dynamic Path/Routes

Sep 8, 2020
Example /new-york/restaurants

_.vue

Edit pages/_.vue

<template>  <div>Hello: {{ $route.params }}</div></template>

$route.params.pathMatch will show the full path, such as new-york or new-york/restaurants.

_

If you want separate .vue files for to handle new-york/restaurants or new-york/hotels, use the following setup.

└── _
    ├── index.vue
    └── restaurants.vue

Edit _/index.vue.

$route.params.pathMatch will show the full path, such as new-york or new-york/hotels.

<template>  <div>Hello: {{ $route.params }}</div></template>

Edit _/restaurants.vue

$route.params.pathMatch will show new-york if the url is new-york/restaurants.

<template>  <div>Restaurants: {{ $route.params }}</div></template>

@nuxtjs/router-extras

Install

npm install --save-dev @nuxtjs/router-extras

Edit nuxt.config.js.

export default {  modules: [    '@nuxtjs/router-extras',  ],}

NOTE: The documentation recommend to use buildModules (only use modules if you are using Nuxt < 2.9.0). I am using Nuxt 2.14.4, and it seems like only modules is working.

└── place
    ├── index.vue
    └── restaurants.vue

Edit place/index.vue.

<router>{  path: '/:urlName'}</router><template>  <div>Place: {{ $route.params.urlName }}</div></template>

Edit place/restaurants.vue

<router>{  path: '/:urlName/restaurants'}</router><template>  <div>Restaurants: {{ $route.params.urlName }}</div></template>

Other Solutions

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.