Nuxt.js: Can't get 'router.addRoutes' working from plugins

Created on 18 Feb 2019  路  5Comments  路  Source: nuxt/nuxt.js

Version

v2.4.3

Reproduction link

https://codesandbox.io/s/2p2jxm6k5y

Some context

The application exposes three different routes :

  1. Home, defined like normal in the router.js file.
  2. About, defined from a plugin.
  3. Contact, defined from a plugin, with a special options property.

Steps to reproduce

  1. Opening the sandbox displays the home page. Since this page is defined like any regular pages, it does work properly.
  2. Navigating to /about shows an error page (Cannot read property 'layout' of undefined)
  3. Navigating to /contact, the page is shown properly.

What is expected ?

Navigating to /about or /contact should work by default, and not need the options property.

What is actually happening?

Navigating to /about shows an error page.

Additional comments?

It does work properly by adding an empty options property. While not being ideal, it can be used to get around this issue.

This bug report is available on Nuxt community (#c8683)
bug-report

Most helpful comment

It will be even easier 鈽猴笍

The module container has a fn built-in for that 鈽猴笍
Docs: https://nuxtjs.org/api/internals-module-container#extendroutes-fn-

Example:

export default function AboutModule () {
  this.extendRoutes((routes) => {
    // Add new routes
    routes.push({
      path: '/about',
      component: {
        render: h => <h1>About</h1>
      }
    })
  })
}

All 5 comments

Any reason you don't use a module or the nuxt.config.js to extend your routes, as it is suggested in the docs?

I may have missed this page from the documentation 馃槆

Do you mean calling something like this ?

export default function AboutModule () {
  this.options.router.extendRoutes = (routes, ...args) => {
    // Keep previously registered routes
    this.options.router.extendRoutes(routes, ...args)

    // Add new routes
    routes.push({
      path: '/about',
      component: {
        render: h => <h1>About</h1>
      }
    })
  }
}

It will be even easier 鈽猴笍

The module container has a fn built-in for that 鈽猴笍
Docs: https://nuxtjs.org/api/internals-module-container#extendroutes-fn-

Example:

export default function AboutModule () {
  this.extendRoutes((routes) => {
    // Add new routes
    routes.push({
      path: '/about',
      component: {
        render: h => <h1>About</h1>
      }
    })
  })
}

@manniL Whoa, I completely missed it when reading the documentation. Sorry about that. I let you decide if this issue should be closed since a solution is available.

Thanks !

Closing here as I think that this recommended way should cover the necessary cases 鈽猴笍

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vadimsg picture vadimsg  路  3Comments

mattdharmon picture mattdharmon  路  3Comments

danieloprado picture danieloprado  路  3Comments

gary149 picture gary149  路  3Comments

msudgh picture msudgh  路  3Comments