Git Product home page Git Product logo

router-module's Introduction

@nuxtjs/router

npm version npm downloads Github Actions CI Codecov License

Nuxt 2 module to use router.js instead of pages/ directory

๐Ÿ“– Release Notes

Nuxt 3

This is now possible to extend vue-router with Nuxt 3 with different methods, learn more on https://nuxt.com/docs/guide/going-further/custom-routing

If you don't have the pages/ directory, make sure to enable Vue Router with:

export default defineNuxtConfig({
  pages: true
})

Features

Use your own router.js to handle your routes into your Nuxt.js application.

Setup

  1. Add @nuxtjs/router dependency to your project
yarn add --dev @nuxtjs/router # or npm install --save-dev @nuxtjs/router
  1. Add @nuxtjs/router to the buildModules section of nuxt.config.js
export default {
  buildModules: [
    // Simple usage
    '@nuxtjs/router',

    // With options
    ['@nuxtjs/router', { /* module options */ }]
  ]
}

โš ๏ธ If you are using Nuxt < v2.9 you have to install the module as a dependency (No --dev or --save-dev flags) and use modules section in nuxt.config.js instead of buildModules.

Using top level options

export default {
  buildModules: [
    '@nuxtjs/router'
  ],
  routerModule: {
    /* module options */
  }
}

If you are using SPA mode, add an index / route to generate section of nuxt.config.js:

export default {
  generate: {
    routes: [
      '/'
    ]
  }
}

Options

path

  • Type: String
  • Default: srcDir

Location of you route file.

fileName

  • Type: String
  • Default: router.js

Name of you route file.

keepDefaultRouter

  • Type: Boolean
  • Default: false

Can access the default router.

parsePages

  • Type: Boolean
  • Default: 'keepDefaultRouter'

Can disable/enable the pages/ directory into Nuxt.

Usage

This module, by default, disable the pages/ directory into Nuxt and will use a router.js file at your srcDir directory:

components/
  my-page.vue
router.js

router.js need to export a createRouter method like this:

import Vue from 'vue'
import Router from 'vue-router'

import MyPage from '~/components/my-page'

Vue.use(Router)

export function createRouter() {
  return new Router({
    mode: 'history',
    routes: [
      {
        path: '/',
        component: MyPage
      }
    ]
  })
}

The components defined as routes have access to the same special attributes and functions (head, asyncData, validate, etc.) as the Nuxt Page component.

Accessing default router

If you use the module with { keepDefaultRouter: true }, you can access the default router:

โš ๏ธ If you are using Nuxt < 2.9.0, the parameter routerOptions is not available.

โš ๏ธ If you are using Nuxt < 2.15.0, the parameter config is not available.

โš ๏ธ If you are using Nuxt < 2.16.0, the parameter store is not available.

export function createRouter(ssrContext, createDefaultRouter, routerOptions, config, store) {
  const options = routerOptions ? routerOptions : createDefaultRouter(ssrContext, config).options

  return new Router({
    ...options,
    routes: fixRoutes(options.routes, store)
  })
}

function fixRoutes(defaultRoutes, store) {
  // default routes that come from `pages/`
  // Filter some routes using the content of the store for example
  return defaultRoutes.filter(...).map(...)
}

Development

  1. Clone this repository
  2. Install dependencies using yarn install or npm install
  3. Start development server using npm run dev

License

MIT License

Copyright (c) Nuxt Community

router-module's People

Contributors

aszaffranietz avatar atinux avatar dependabot[bot] avatar galvez avatar harlan-zw avatar ilyasemenov avatar loick avatar mornir avatar pi0 avatar renovate-bot avatar renovate[bot] avatar ricardogobbosouza avatar robyedlin avatar tjark-kuehl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

router-module's Issues

multiple named views cause router.js contains syntax error

Version

v2.4.3

Reproduction link

https://github.com/kdeng/nuxt-named-view-sample

Steps to reproduce

  1. Run npm i
  2. Run npm run dev

What is expected ?

I expected router.js can be generated properly, and named view can be rendered properly.

What is actually happening?

router.js has been generated with syntax error.


 ERROR  Failed to compile with 1 errors                                                                                                                                                                                                                   friendly-errors 22:13:34


 ERROR  in ./.nuxt/router.js                                                                                                                                                                                                                              friendly-errors 22:13:34

Syntax Error: Unexpected token, expected "," (86:8)                                                                                                                                                                                                       friendly-errors 22:13:34

  84 |         default: _708facd7,
  85 |         footer: _03b372e3
> 86 |         default: _6fab42f0,
     |         ^
  87 |         top: _6b7085a2
  88 |       },
  89 |       name: "main"

                                                                                                                                                                                                                                                          friendly-errors 22:13:34
 @ ./.nuxt/index.js 8:0-43 59:19-31
 @ ./.nuxt/client.js
 @ multi eventsource-polyfill webpack-hot-middleware/client?reload=true&timeout=30000&ansiColors=&overlayStyles=&name=client&path=/__webpack_hmr/client ./.nuxt/client.js
                                                                                                                                                                                                                                                          friendly-errors 22:13:34
โ„น Waiting for file changes

Additional comments?

I am new to nuxtjs, and try to play around about named views for enabling master footer component for cart router, I am not sure whether it is my mistake or router module bug. Cheers.

This bug report is available on Nuxt community (#c35)

Router module with mode: 'spa'

I'm getting an error that there is a missing /dist/index.html file when running a build with mode: 'spa' in nuxt.config.js.

Am I missing a config, or is this a bug?

This question is available on Nuxt.js community (#c3)

```

This question is available on Nuxt community (#c23)

Module not found: Error: Can't resolve 'fs'

When I nuxt or nuxt build, I get this error:

ERROR in ./node_modules/@nuxtjs/router/dist/index.js
Module not found: Error: Can't resolve 'fs' in 'MY_PROJECT\node_modules\@nuxtjs\router\dist'
 @ ./node_modules/@nuxtjs/router/dist/index.js 4:9-22
 @ multi vue vue-router vue-meta vuex @nuxtjs/router
Error: Webpack build exited with errors
    at MY_PROJECT\node_modules\nuxt\lib\builder\builder.js:498:27
    at emitRecords.err (MY_PROJECT\node_modules\webpack\lib\Compiler.js:269:13)
    at Compiler.emitRecords (MY_PROJECT\node_modules\webpack\lib\Compiler.js:375:38)
    at emitAssets.err (MY_PROJECT\node_modules\webpack\lib\Compiler.js:262:10)
    at applyPluginsAsyncSeries1.err (MY_PROJECT\node_modules\webpack\lib\Compiler.js:368:12)
    at next (MY_PROJECT\node_modules\tapable\lib\Tapable.js:218:11)
    at Compiler.compiler.plugin (MY_PROJECT\node_modules\webpack\lib\performance\SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (MY_PROJECT\node_modules\tapable\lib\Tapable.js:222:13)
    at Compiler.afterEmit (MY_PROJECT\node_modules\webpack\lib\Compiler.js:365:9)
    at require.forEach.err (MY_PROJECT\node_modules\webpack\lib\Compiler.js:354:15)
    at MY_PROJECT\node_modules\async\dist\async.js:421:16
    at iteratorCallback (MY_PROJECT\node_modules\async\dist\async.js:998:13)
    at MY_PROJECT\node_modules\async\dist\async.js:906:16
    at MY_PROJECT\node_modules\graceful-fs\graceful-fs.js:43:10
    at FSReqWrap.oncomplete (fs.js:135:15)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `nuxt build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\John\AppData\Roaming\npm-cache\_logs\2017-10-18T12_11_19_032Z-debug.log
This question is available on Nuxt.js community (#c7)

Custom router in .nuxt folder

  1. If i add custom router in .nuxt folder, this fragment create relative link, but for .nuxt folder it hasn't dot prefix, for example path to .nuxt/custom-router.js is custom-router.js, webpack try find package
    routerFilePath: relative(this.options.buildDir, routerFilePath).replace(/\/+|\\+/g, '/'),

    Example:
['@nuxtjs/router', {
  keepDefaultRouter: true,
  path: path.resolve(__dirname, './.nuxt'),
  fileName: 'cache-router.js',
}],
  1. I can't create custom-router.js before @nuxtjs/router check is file exist. Simple module.addTemplate worked only for second time (first time generate file) and writeFileSync create file before nuxt generate files, therefore nuxt delete it. Only one worked variant is generate file with writeFileSync in srcDir
    if (!existsSync(routerFilePath)) {

Examples of module that overwrite router madhusudanbabar/k-domains and

https://github.com/Kolobok12309/vue-router-webcache/blob/f5411bc54e72efcd78f5ec8153b4a52965f80515/lib/nuxt/index.ts#L40-L46

render function or template not defined in component: anonymous

Version

v1.3.0

Reproduction link

https://github.com/mahdikmg/nuxt-router-module-bug

Steps to reproduce

just install dependencies, run the project and open it in your browser.
Screenshot from 2020-09-22 13-52-02.png

What is expected ?

when i open project in browser it happens and prevent page to render.

What is actually happening?

when i remove '@nuxtjs/router' from build modules in nuxt.config.js file, the error will solve.

Additional comments?

any help will appreciated

This bug report is available on Nuxt community (#c61)

Get routes.js file from api call

I posted about this here but thought I'd try again here as its more relevant.

I'm running Nuxt as the frontend to a cms so need to get the pages from an api call, can I get the pages from nuxtServerInit then loop through them in router.js to create the routes.

Or I could programatically create a valid routes.js on the CMS side if i could then fetch it from Nuxt somehow.

Thanks

This question is available on Nuxt.js community (#c1)

Make it work with Nuxt 2.14

What problem does this feature solve?

Enable the router module to work. with Nuxt 2.14, it is not working atm.

This feature request is available on Nuxt community (#c59)

Support for windows paths

Version

v1.3.0

Reproduction link

[// windows node.js needed](// windows node.js needed)

Steps to reproduce

Building NUXT project with @nuxtjs/router module on windows node.js
fail by compile error:

This dependency was not found:
outer.js in ./.nuxt/router.js
outer.jsll it, you can run: npm install --save ..

What is expected ?

in generated @/.nuxt/router.js:

import { createRouter as customCreateRouter } from '../router.js'
// ..
```.

### What is actually happening?

in generated `@/.nuxt/router.js`:

import { createRouter as customCreateRouter } from '..\router.js'
//...

windows backslash resolve to escaped \r in windows

### Additional comments?

Windows node returns backshash in relative paths:
https://nodejs.org/api/path.html#path_path_relative_from_to

fixing `@nuxtjs\router\lib\module.js` line  31:
  routerFilePath: relative(this.options.buildDir, routerFilePath).replace(/\/+|\\+/g, '/'),
...solves the problem
original line:
  routerFilePath: relative(this.options.buildDir, routerFilePath).replace(/\/+/g, '/'),
...replaces only slash, not backslash

<!--cmty--><!--cmty_prevent_hook-->
<div align="right"><sub><em>This bug report is available on <a href="https://cmty.app/nuxt">Nuxt</a> community (<a href="https://cmty.app/nuxt/router-module/issues/c34">#c34</a>)</em></sub></div>

Nuxt dynamic routes, addRoutes ssr, 404 or Cannot read property 'layout' of undefined error or can't access property "scrollToTop", Page.options is undefined

The problem with adding routes dynamically
In the production version, I plan to use an ajax request that gives the "page type" in the plugin and add the appropriate routes. For the demonstration, I created the minimum set of code required to run and test the dynamic addition of routes, please see

My nuxt.config.js

module.exports = {
  ssr: true,
  mode: 'universal',
  srcDir: __dirname,
  loading: { color: '#007bff' },
    plugins: [
      {src: '~/plugins/route'}
    ],
 modules: [
    "@nuxtjs/axios",
    [
      'nuxt-i18n', {
      parsePages: false,
      pages: {
        contacts: {
          en: '/kont_test2',
          uk: '/kont_test3',
          ru: '/kont_test4',
      }},

      strategy:'prefix_except_default',
      detectBrowserLanguage: {
        useCookie: true,
        cookieKey: 'i18n_redirected',
        alwaysRedirect: true,
        fallbackLocale: 'en'
      },
      vueI18nLoader: true,
      locales: [
        {
          name: 'English',
          code: 'en',
          iso: 'en-US',
          file: 'en.js'
        },
        {
          name: 'ะ ัƒััะบะธะน',
          code: 'ru',
          iso: 'ru-RU',
          file: 'ru.js'
        },
        {
          name: 'ะฃะบั€ะฐั—ะฝััŒะบะฐ',
          code: 'uk',
          iso: 'uk-UA',
          file: 'uk.js'
        },
      ],

      lazy: true,
      loadLanguagesAsync: true,
      silentTranslationWarn:true,
      langDir: 'locales/',
      defaultLocale: 'ru',


    },
    ],],
  hooks: {
    generate: {
      done (generator) {
        // Copy dist files to public/_nuxt
        if (generator.nuxt.options.dev === false && generator.nuxt.options.mode === 'spa') {
          const publicDir = join(generator.nuxt.options.rootDir, 'public', '_nuxt')
          removeSync(publicDir)
          copySync(join(generator.nuxt.options.generate.dir, '_nuxt'), publicDir)
          copySync(join(generator.nuxt.options.generate.dir, '200.html'), join(publicDir, 'index.html'))
          removeSync(generator.nuxt.options.generate.dir)
        }
      },

    }
  },
  build: {
    extend (config, { isDev, isClient }) {
      config.node = {
        fs: "empty"
      }
    }
  }

}

In the config I add plugin "route", plugins/route.js source code

function interopDefault(promise) {
  return promise.then(m => m.default || m);
}


export default ({app, router, routeres}) => {

  //axios.defaults.baseURL = process.env.apiUrl;
  // console.log(app.router);
  //afterEach

  app.router.beforeEach((to, from, next) => {

    const matched = app.router.getMatchedComponents(to);
    console.log("matched: " + matched.length);
    console.log("to.path: " + to.path);


    let dynamicView = () => interopDefault(import('~pages/post.vue'));
   
    if (!matched.length) {
      console.log('not-exist');

      app.router.addRoutes([
        {
          path: to.path,
          component: dynamicView,    
        }], { override: true });


      next(to.path);

      
    } else {
      console.log('route exist');
      next()     
    }
    
  })
}

pages/post.vue

<template>
    <div class = "test">test post page for this path</div>
</template>

<script>
    export default {
       
    }
</script>

ะกode is quite simplified, when checking if (! Matched.length) we add a simple march page "pages / post.vue" and should display the simple text "test post page for this path"
For example, by contacting any url that does not exist, the route should be added.
example.com/other_url
From time to time I see errors:
Cannot read property 'scrollToTop' of undefined (for now)
Cannot read property 'layout' of undefined error (periodically)
404 page not found (periodically)

Link to "codesandbox"
https://codesandbox.io/s/nuxt-nuxt-i18n-issue-1044-forked-t33du

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Using npm packages for Renovate presets is now deprecated. Please migrate to repository-based presets instead.

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/setup-node v2
  • actions/checkout v2
  • actions/cache v2
  • codecov/codecov-action v2
npm
package.json
  • consola ^2.15.3
  • defu ^5.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

overlapping in defining routes in nuxtjs router

Version 1.5.0

I'm trying to develop a blog with nuxtjs. But I have problem with routing.
I define this route localhost/@:username/:slug to show a post. also I want to have these routes:
localhost/@:username/edit, localhost/@:username/posts, localhost/@:username/followers, ...

But it makes disturbance, and all of them route to show post page.

my router:


import Vue from 'vue';
import Router from 'vue-router';
import {scrollBehavior} from '~/utils';

Vue.use(Router);

const page = path => () => import(`~/pages/${path}`).then(m => m.default || m);

const routes = [
    {
    path: '/@:username',
    component: page('user/profile/index.vue'),
    children: [
        {path: '', name: 'profile', component: page('user/profile/profile.vue'),},
        {path: 'edit', name: 'profile-edit', component: page('user/profile/edit.vue')},
        {path: 'following', name: 'profile-following', component: page('user/profile/following.vue')},
        {path: 'followers', name: 'profile-followers', component: page('user/profile/followers.vue')},
     ]
    },
    {path: '/@:username/:slug', name: 'post', component: page('site/posts/show-post.vue')},
];

export function createRouter() {
    return new Router({
        routes,
        scrollBehavior,
        mode: 'history'
    });
}

typescript does not work

ERROR Nuxt error

Error: [nuxt-router-module] Please create a router.js file in your source folder.

This question is available on Nuxt.js community (#c12)

Use only in server side.

Hi @Atinux , in my case i need take routes by ip user and host, but if i use context in createRouter function i get [nuxt] Error while mounting app: TypeError: Cannot read property 'req' of undefined. Can i use router only in server side?

Code:

import Vue from 'vue';
import Router from 'vue-router';
import generateRoutes from '~/helpers/generateRoutes';


Vue.use(Router);

export const createRouter = async (context) => {
  const host = context.req.headers.host;
  const ip = context.req.headers['x-forwarded-for'] || context.req.connection.remoteAddress;
  return new Router({
    mode: 'history',
    routes: await generateRoutes(host, ip),
  });
};
const generateRoutes = async (host, ip) => {
  const resultRouters = router;
  if (host.indexOf('exemple1.com') !== -1) {
    resultRouters.unshift(
      {
        path: '/',
        name: 'page',
        component: page,
      },
    );
    return resultRouters;
  }
  if (host.indexOf('exemple2.com'') !== -1) {
    resultRouters.unshift(
      {
        path: '/',
        name: 'page2',
        component: page2,
      },
    );
    return resultRouters;
  }
  if (host.indexOf('exemple3.com'') !== -1) {
    resultRouters.unshift(
      {
        path: '/',
        name: 'page3',
        component: page3,
      },
    );
    return resultRouters;
  }
  const location = await generateRoutersByLocations(ip);
  if (location.toLowerCase() === 'au' || location.toLowerCase() === 'nz') {
    resultRouters.unshift(
      {
        path: '/',
        name: 'page4',
        component: page4,
      },
    );
    return resultRouters;
  }
  resultRouters.unshift(
    {
      path: '/',
      name: 'mainPage',
      component: mainPage,
    },
  );
  return resultRouters;
};

export default generateRoutes;
const generateRoutersByLocations = async (ip) => {
  const { headers } = await axios.get(urls.apiUrl + urls.initPage, { params: { ip } });
  const location = headers['x-geo-ip-country'];
  return location;
};

export default generateRoutersByLocations;
This question is available on Nuxt community (#c36)

router.js is ignored from eslint-loader linting

What I expect to happen

I expect that my pre loader configuration will lint this file.

That's how I configure it:

        // Enabling eslint in nuxt.config.js:
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })

What actually happens

router.js is just ignored from linting.
You can write any styles you want, nothing will happen.

It only happens with the file. Other files are linted as usual.

Steps to reproduce

  1. Install https://github.com/wemake-services/wemake-vue-template
  2. Mess up something inside router.js for example: mode:'history', (no spaces)
  3. Run yarn dev

There will be no error. But there should be one.

Comments

I guess it happens because webpack does not actually require() this file during the client build.
Related: wemake-services/wemake-vue-template#587

PS

I have tried to submit a bug via cmty twice! At the first try it just removed everything I had and showed me this message (I was unable to select any version):
2018-06-09 22 21 19

Then it just went offline (but I have already copied my issue text this time!):
2018-06-09 22 22 31

Action required: Greenkeeper could not be activated ๐Ÿšจ

๐Ÿšจ You need to enable Continuous Integration on all branches of this repository. ๐Ÿšจ

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you donโ€™t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Once you have installed CI on this repository, youโ€™ll need to re-trigger Greenkeeperโ€™s initial Pull Request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integrationโ€™s white list on Github. You'll find this list on your repo or organiszationโ€™s settings page, under Installed GitHub Apps.

This question is available on Nuxt.js community (#c5)

npm run generate error on routes

Since I used your module, I'm not able to generate a static website `yarn run generate'

here the error

TypeError: Cannot read property 'forEach' of undefined
    at flatRoutes (/Users/nicolashusson/www/shingrix/htdocs/node_modules/nuxt/dist/nuxt.js:1288:9)
    at Generator._callee2$ (/Users/nicolashusson/www/shingrix/htdocs/node_modules/nuxt/lib/builder/generator.js:62:66)
    at tryCatch (/Users/nicolashusson/www/shingrix/htdocs/node_modules/nuxt/node_modules/regenerator-runtime/runtime.js:65:40)
    at Generator.invoke [as _invoke] (/Users/nicolashusson/www/shingrix/htdocs/node_modules/nuxt/node_modules/regenerator-runtime/runtime.js:299:22)
    at Generator.prototype.(anonymous function) [as next] (/Users/nicolashusson/www/shingrix/htdocs/node_modules/nuxt/node_modules/regenerator-runtime/runtime.js:117:21)
    at step (/Users/nicolashusson/www/shingrix/htdocs/node_modules/nuxt/dist/nuxt.js:954:30)
    at /Users/nicolashusson/www/shingrix/htdocs/node_modules/nuxt/dist/nuxt.js:965:13

indeed, in node_modules/nuxt/dist/nuxt.js, function flatRoutes(router)
router is undefined...

This question is available on Nuxt.js community (#c9)

next() function is not working well

Getting "page not found" when next called

my router.js

...
import { routeMetaPrepare } from './routeMetaPrepare';

import routesAuth from './group/auth';
....
Vue.use(Router);

const routeList = [
  routesAuth,
  ...
];

for (let i = 0; i < routeList.length; i++) {
  for (let j = 0; j < routeList[i].length; j++) {
     routes.push(routeMetaPrepare(routeList[i][j]));
   }
}

export function createRouter() {
  return new Router({
    mode: 'history',
    routes
  });
}

routeMetaPrepare has logic to check auth state and pass or redirect user

export const ifAuthenticated = (to, from, next) => {
  const { authSuccess } = useAuth();
  if (authSuccess.value) {
    next();
    return;
  }
  next('/signin');
};

export const routeMetaPrepare = (routeInfo) => {
  const meta = routeInfo.meta || {};

  switch (meta.auth) {
    case 'AUTH':
      routeInfo.beforeEnter = ifAuthenticated;
      break;
    default:
      break;
  }

  const children = routeInfo.children || [];
  for (let i = 0; i < children.length; i++) {
    routeInfo.children[i] = routeMetaPrepare(children[i]);
  }

  routeInfo.meta = meta;
  return routeInfo;
};

if a user has no access then next func will be called. But next will redirecting to 404. It seems like there is no signin page.

Don't require /router.js in production .. it's not even used

What problem does this feature solve?

Currently after you do a build and deploy to a server, you have to include /router.js even though it ISN'T EVEN USED!
It would be nice to wrap most of this module in a build hook since that's all it's really dealing with anyway.

This feature request is available on Nuxt community (#c31)

children in route.js don't work

In my route.js I implemented children url as you can see:

{ path: '/onstep', name: 'OnStep', component: OnstepMain, children: [ { path: 'cosa-e-onstep', name: 'Cosa รจ OnStep', component: CosaOnStep }, { path: 'configurazioni-possibili-di-onstep', name: 'Configurazioni Possibili', component: ConfOnStep }, { path: 'moduli-necessari-per-la-scheda', name: 'Moduli Necessari', component: ModuliNecessari }, { path: 'scelta-del-driver-per-motori-passo-passo', name: 'Scelta Del Driver Per Motori Passo Passo', component: SceltaDriver }, { path: 'funzionamento-scelta-motori-passo-passo', name: 'Scelta e Funzinamento dei Motori Passo Passo', component: SceltaStepper }, { path: 'calcolo-step-grado-montatura-eq-o-azm', name: 'Calcolo degli step/grado di una montatura EQ o AZM', component: CalcoloStep }, { path: 'montare-la-scheda', name: 'Montare la Scheda', component: MontaScheda }, { path: 'prepariamoci-a-scaricare-il-firmware', name: 'Preprariamo il PC', component: PreparaPC }, { path: 'download-configurazione-firmware-onstep', name: 'Impostare il firmware di OnStep', component: FwOnstep }, { path: 'configurazione-firmware-wifi', name: 'Impostare il firmware del WiFi', component: FwWiFi }, { path: 'download-firmware-onstep', name: 'Download Firmware OnStep', component: DwOnstep }, ] },

But the pages are not reachable, olso printing il console all the route aviable, I have only parten page, why?

error 404

I followed the documentation guide did everything as is, but all routes come out as 404 not found
router.js

import Vue from "vue";
import Router from "vue-router";


Vue.use(Router);

export function createRouter() {
  return new Router({
    mode: "history",
    routes: [
      {
        name: "index",
        path: "",
        component: () => import("@/views/index")
      },
      {
        name: "analytics",
        path: "/analytics",
        component: () => import("@/views/analytics")
      },
      {
        name: "titles",
        path: "/titles",
        component: () => import("@/views/titles/index")
      },
      {
        name: "titles-create",
        path: "/titles/create",
        component: () => import("@/views/titles/create")
      },
      {
        name: "titles-id-edit",
        path: "/titles/:id/edit",
        component: () => import("@/views/titles/_id/edit")
      },
      {
        name: "people",
        path: "/people",
        component: () => import("@/views/people/index")
      },
      {
        name: "people-create",
        path: "/people/create",
        component: () => import("@/views/people/create")
      },
      {
        name: "people-id-edit",
        path: "/people/:id/edit",
        component: () => import("@/views/people/_id/edit")
      },
      {
        name: "links",
        path: "/links",
        component: () => import("@/views/links")
      },
      {
        name: "users",
        path: "/users",
        component: () => import("@/views/users")
      },
      {
        path: "/settings",
        component: () => import("@/views/settings"),
        children: [
          {
            path: "",
            component: () => import("@/views/settings/index"),
            name: "settings"
          },
          {
            path: "analytics",
            component: () => import("@/views/settings/analytics"),
            name: "settings-analytics"
          },
          {
            path: "auth",
            component: () => import("@/views/settings/auth"),
            name: "settings-auth"
          },
          {
            path: "cache",
            component: () => import("@/views/settings/cache"),
            name: "settings-cache"
          },
          {
            path: "mail",
            component: () => import("@/views/settings/mail"),
            name: "settings-mail"
          },
          {
            path: "recaptcha",
            component: () => import("@/views/settings/recaptcha"),
            name: "settings-recaptcha"
          },
          {
            path: "upload",
            component: () => import("@/views/settings/upload"),
            name: "settings-upload"
          },
          {
            path: "/superadmin/permissions",
            component: () => import("@/views/superadmin/permissions"),
            name: "superadmin-permissions"
          },
          {
            path: "/superadmin/roles",
            component: () => import("@/views/superadmin/roles"),
            name: "superadmin-roles"
          }
        ]
      }
    ]
  });
}

nuxt: 2.11
@nuxtjs/router: 1.5.0
os: macos

This question is available on Nuxt community (#c51)

Probleme component refresh !

hello, my component this refresh when I change the url !
But I do not have this problem without nuxt !
An idea ? thx ๐Ÿ˜‡

`{ path: '/komit', name: 'main_komit', component: main_komit },

{ path: '/create/komit', name: 'create_komit', component: main_komit },`

This question is available on Nuxt community (#c24)

[2.15] keepDefaultRouter option broken

Ref: nuxt/nuxt#8831

Since 2.15, we are passing two arguments to createRouter utility (for runtime config support). We should either pass config as 4th argument from createRouter to user provided createRouter function and update docs or wrap imported createRouter from nuxt to do this.

How to access store from router-module nuxt^2.8.1 ?

I'm using nuxt version 2.8.1 and the new structure Vuex Mode with modules.
https://nuxtjs.org/guide/vuex-store#activate-the-store

About the classic mode vuex: This feature is deprecated and will be removed in Nuxt 3.

About router, i'm using vue-router module to management from route.

I'm using the vue-router module for route management and have been unable to access the data from my "store" in my ~/router.js file.

My structure code
/store

  • user.js
  • lang.js

/router.js

I want to access the stored data from my ~/router.js file, how can I do that?

This question is available on Nuxt community (#c38)

Subdomain routing

What problem does this feature solve?

By default, nuxt creates the URL from the pages folder, for example :

/pages/blog/index.vue = mywebsite.com/blog
/pages/blog/posts/index.vue = mywebsite.com/blog/posts

It's super convenient, our URLs match our file architecture, no problems.

However, there is no option to change the behavior of the router to allow the folder to point to a subdomain of the same name, for example :

/pages/blog/index.vue = blog.mywebsite.com
/pages/blog/posts/index.vue = blog.mywebsite.com/posts

I know it's impossible to change the client-side URL without reloading the page and so vue-router can not do it, however nuxt-i18n allows you to use a subdomain to change language and after my research, using NuxtServerInit it would be possible to create an alternative, something that I started to do but I have not managed to go all the way. ๐Ÿ˜”

My try :
https://gitlab.com/ankaworld/ankaworld.net/merge_requests/1/diffs

My research :
https://cmty.app/nuxt/nuxt.js/issues/c2076
nuxt/nuxt#2378
vuejs/vue-router#1611

This is my first issue on Nuxt community, it will surely lack explanations, details or other so do not hesitate to propose changes but do not be aggressive ๐Ÿ˜„

This feature request is available on Nuxt community (#c28)

Lazy loading

Hi there. Thank you for your module.
I am trying to use it in my project instead pages mechanism. Everything are going fine except lazy-loading (eg. code splitting)

I tried to use this configuration, like in Vue-router docs but it doesn't work somehow

import Router from "vue-router"

import Main from "~/components/Main"

const Customer = () => import("~/components/customer/index.vue");


// import Customer from "~/components/customer";
import Overview from "~/components/customer/overview";
import Profile from "~/components/customer/profile";
import Cards from "~/components/customer/cards";

Vue.use(Router);

export function createRouter() {
	return new Router({
		mode: "history",
		routes: [
			{
				path: "/",
				component: Main
			},
			{
				path: "/customer",
				component: Customer,
				children: [
					{
						path : "",
						component : Overview
					},
					{
						path : "profile",
						component : Profile
					},
					{
						path : "cards",
						component : Cards
					}
				]
			}
		]
	})
}

When I tried to load the Customer module I got this issue
Failed to mount component: template or render function not defined.

My component is deadly simple

<template>
    <router-view></router-view>
</template>

<script lang="ts">

	import Vue from "vue";
	import Component from "nuxt-class-component";

	@Component
	export default class extends Vue {}
</script>

could you, please, help me with this issue? May be I'm doing something wrong.

This question is available on Nuxt.js community (#c11)

Router.push doesn't return a Promise

Version

v1.3.0

Reproduction link

https://codesandbox.io/s/vigilant-booth-27tv8?file=/pages/index.vue

Steps to reproduce

Run a sandbox project
Call this.$router.push("/about"); in the component
Watch the returned value

What is expected ?

push should return a Promise if it is not given an onComplete and onAbort parameter and Promises are supported.

From https://router.vuejs.org/guide/essentials/navigation.html

In 3.1.0+, you can omit the 2nd and 3rd parameter and router.push/router.replace will return a promise instead if Promises are supported.

What is actually happening?

push is returning undefined.

Additional comments?

Here is the incriminated line that for some reason replaces the push function and uses a default parameter for onComplete, which prevents the original function from ever returning a Promise.

https://github.com/nuxt/nuxt.js/blob/e8aca9eb117851047e82e94948ff8b4bcb464b1a/packages/vue-app/template/router.js#L89

This bug report is available on Nuxt community (#c67)

SPA in subdirectory/router base.

Generating an SPA with a router base set will automatically add a <base href=""> so the application can be loaded in a subdirectoy.

Can this be accomplished when using the router-module or will i need to set the base-href and rewrite all script tags myself?

This question is available on Nuxt.js community (#c8)

named index.vue files

What problem does this feature solve?

It can get a bit confusing/annoying when you have 30 index.vue, or 10 _id.vue files

What does the proposed changes look like?

the ability to add a name to a dynamic file which is ignored.

e.g. index.users.vue _id.classes.vue index.homepage.vue

This feature request is available on Nuxt community (#c49)

base route is appended to url on page referesh

With simple latest nuxt app, if you add @nuxtjs/router and set router base to anything, each browser refresh appends base route to the url.

image

package.json

  "name": "my-app",
  "scripts": {
    "dev": "nuxt",
  },
  "dependencies": {
    "nuxt": "^2.15.6"
  },
  "devDependencies": {
    "@nuxtjs/router": "1.6.1"
  }
}

nuxt.config.js

  ssr: false,

  router: {
    base: "/s"
  },


  buildModules: [
    "@nuxtjs/router",
  ],

};

router.js

import Vue from 'vue'
import Router from 'vue-router'

import MyPage from '~/my-page'

Vue.use(Router)

export function createRouter() {
  return new Router({
    mode: 'history',
    routes: [
      {
        path: '/',
        component: MyPage
      }
    ]
  })
}

nuxt generate - no such file or directory

With fresh Nuxt and router-module 1.0.1, nuxt generate produces the following error:

Generating routes
{ Error: ENOENT: no such file or directory, lstat '/home/ubuntu/workspace/dist/index.html'
    at Error (native)
  errno: -2,
  code: 'ENOENT',
  syscall: 'lstat',
  path: '/home/ubuntu/workspace/dist/index.html' }
This question is available on Nuxt.js community (#c4)

Invalid component name: "pages/product/_slug.vue". Component names should conform to valid custom element name in html5 specification.

Version

v1.3.0

Steps to reproduce

I have some dynamic routes. My folder structure is this:

- pages
 - product
  - _slug.vue

I link to the route like this:

<nuxt-link :to="{ name: 'product-slug', params: { slug: product.slug } }">

It works fine, it shows the correct URL and also directs the page fine, however, I am getting an annoying red error in my console:

[Vue warn]: Invalid component name: "pages/product/_slug.vue". Component names should conform to valid custom element name in html5 specification.

enter image description here

I have found this issue, but to little avail: nuxt/nuxt#165

What is expected ?

No error should be outputted

What is actually happening?

An error is being outputted even though it links just fine

This bug report is available on Nuxt community (#c50)

Hydratation error with SSG

Hey !
I've been converting my app from nuxt automatic routing to this module so I can have more freedom with routes (in static generation mode) and got an error while accessing pages.

TypeError: undefined is not an object (evaluating 'c.fetch[this._fetchKey]') โ€” 

Which seems to appear in here https://github.com/nuxt/nuxt.js/blob/dev/packages/vue-app/template/mixins/fetch.client.js#L41

I might be wrong but I think it's coming from data hydratation between the cdn page's content & client.
I made a test with a simple component with asyncData

<template>
  <div>{{ i18n }}</div>
</template>

<script>
export default {
  asyncData() {
    return {
      i18n: {
        foo: 'bar',
      },
    }
  },

& that's the result from the page

image

As you can see window._NUXT_ doesn't contain data.

This is my conf

// nuxt.config.js
buildModules: [
  [
    '@nuxtjs/router',
    {
      path: './core/',
      fileName: 'router.js',
    },
  ],
],
generate: {
  routes: [
    ROUTES.payments.path,
    ROUTES.login.path,
    ROUTES.informations.path,
    ROUTES.deliveries.path,
    ROUTES.companions.path,
  ],
},

// router.js
import Vue from 'vue'
import Router from 'vue-router'
import { ROUTES } from './routes'

Vue.use(Router)

const createRoutes = () => {
  return Object.values(ROUTES).map((route) => {
    return { ...route, pathToRegexpOptions: { strict: true } }
  })
}

export function createRouter() {
  return new Router({
    mode: 'history',
    routes: createRoutes(),
  })
}

// routes.js
import { importDefault } from './utils'

const index = () => importDefault(import('@/pages/index'))
const payments = () => importDefault(import('@/pages/payments'))

export const ROUTES = {
  homePage: {
    path: '/',
    component: index,
  },
  payments: {
    path: '/payments/',
    name: 'payments',
    component: payments,
  },
  // etc.
}
"@nuxtjs/router": "^1.5.1",
"nuxt": "^2.14.6",

Am I doing something wrong ?
Would love to have your feedback quickly as this bug is pretty annoying for us. ๐Ÿ™
Thanks !

Best way to Write API in Nuxt and Router Module?

I'm finding best way to write API.
Currently, i write api like this:

<template>
  <div class="row flex">
    {{data.id}}
  </div>
</template>
<script>
  import axios from 'axios'
  import Item from '~/components/feeds/Post.vue'
  export default {
    data () {
      return {
        data: {}
      }
    },
    mounted () {
      this.asyncData()
    },
    methods: {
      async asyncData (params) {
        let { data } = await axios.get('http://localhost:8000/api/v1/feeds/' + this.$route.params.id + '/')
        this.data = data
      }
    },
    components: {
      'post-detail': Item
    }
  }
</script>

But when I get children data: {{data.user.username}}, the data.user goes undefined. Is this the best way to write API data in Nuxt and Router Module?

This question is available on Nuxt.js community (#c6)

router-module not working in latest version

my router.js is written like this:

import rewardRoutes from '~/routers/reward-router'
import taskRoutes from '~/routers/task-router'

const routes = [
  {
    path: '/',
    component: index,
    children: [
      {
        path: '',
        component: index
      },
      {
        path: 'task',
        component: task,
        children: taskRoutes
      },
      {
        path: 'reward',
        component: reward,
        children: rewardRoutes
      }
    ]
  }
]
export function createRouter () {
  return new VueRouter({
    mode: 'history',
    routes
  })
}

now, when navigate to a page, the url is changed, but the target page is not rendered.

This question is available on Nuxt.js community (#c14)

Scroll position

Version

v1.4.0

Reproduction link

https://github.com/Frankwarnaar/nuxt-router-scrollposition-issue-demo

Steps to reproduce

Navigate to https://quizzical-villani-0e65e2.netlify.com (a deploy of the repo I provided). Scroll a bit down and then click the Other page link. Then click browser back.

What is expected ?

The scroll position should be the same as before leaving the page.

What is actually happening?

The scroll position is reset.

Additional comments

I'm running with the keepDefaultRouter option set to true. My router can be found in src/router.js. I've been trying to debug the issue, by providing a scrollPosition function to my router. Somehow the savedPosition argument was always { x: 0, y: 0 }, .

This bug report is available on Nuxt community (#c42)

Nuxt content not generate or parse to custom router

my content folder file look like this
image

and the target pages look like this
image

in default setting when i not use this package the nuxt content was generate with the text inside .md into .html in dist folder
but when i use this package the .md text not parse into .html in the dist directory

this my generate on nuxt.config.js
image

this my other project when i not use this package, the text from .md was parse to .html in dist directory
image

and now my project when use this package there nothing to parse to .html in dist directory file, there generate the html file with empty text from .md

any suggest or maybe i wrong to put the code, please give me a example code if i wrong i really apreciate it,
thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.