nuxt-community / router-module Goto Github PK
View Code? Open in Web Editor NEWNuxt 2 module to use router.js instead of pages/ directory.
License: MIT License
Nuxt 2 module to use router.js instead of pages/ directory.
License: MIT License
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?
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)/
})
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.
router.js
for example: mode:'history',
(no spaces)yarn dev
There will be no error. But there should be one.
I guess it happens because webpack
does not actually require()
this file during the client build.
Related: wemake-services/wemake-vue-template#587
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):
Then it just went offline (but I have already copied my issue text this time!):
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
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 !
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 },`
keepDefaultRouter
option Cannot find module 'nuxt/lib/app/router'
App should start up normally.
Error: Cannot find module 'nuxt/lib/app/router'
[// windows node.js needed](// windows node.js needed)
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 ..
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>
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
/router.js
I want to access the stored data from my ~/router.js file, how can I do that?
There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.
Error type: Cannot find preset's package (@nuxtjs)
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.
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
}
]
})
}
https://github.com/kdeng/nuxt-named-view-sample
npm i
npm run dev
I expected router.js can be generated properly, and named view can be rendered properly.
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
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.
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?
It can get a bit confusing/annoying when you have 30 index.vue, or 10 _id.vue files
the ability to add a name to a dynamic file which is ignored.
e.g. index.users.vue _id.classes.vue index.homepage.vue
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.
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.
I have found this issue, but to little avail: nuxt/nuxt#165
No error should be outputted
An error is being outputted even though it links just fine
https://github.com/Frankwarnaar/nuxt-router-scrollposition-issue-demo
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.
The scroll position should be the same as before leaving the page.
The scroll position is reset.
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 }
, .
well how to add meta indomation in router.js thanks
🚨 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.
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.
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...
https://github.com/mahdikmg/nuxt-router-module-bug
just install dependencies, run the project and open it in your browser.
when i open project in browser it happens and prevent page to render.
when i remove '@nuxtjs/router' from build modules in nuxt.config.js file, the error will solve.
any help will appreciated
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.
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 😄
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.
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
Hi,
Any way to keep Nuxt default scrollBehavior function ?
When using router-module, this function is lost, so my page scroll position is saved when I navigate.
Nuxt should scrollToTop by default, but there's quite a bit of logic to determine this.
https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-router#scrollbehavior
https://github.com/nuxt/nuxt.js/blob/dev/packages/vue-app/template/router.scrollBehavior.js
.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 packageLine 50 in 18bb2d3
['@nuxtjs/router', {
keepDefaultRouter: true,
path: path.resolve(__dirname, './.nuxt'),
fileName: 'cache-router.js',
}],
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
Line 40 in 18bb2d3
Examples of module that overwrite router madhusudanbabar/k-domains and
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?
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' }
my content folder file look like this
and the target pages look like this
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
this my other project when i not use this package, the text from .md was parse to .html in dist directory
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.
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
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;
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'
});
}
https://github.com/AyozeM/nuxt-router-example
Install dependencies
Show router.js to check routes.
npm run generate
That each route definition generate static html page, as defatult nuxt router.
No generate static pages from router.js
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.
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 issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These problems occurred while renovating this repository. View logs.
These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
.github/workflows/ci.yml
actions/setup-node v2
actions/checkout v2
actions/cache v2
codecov/codecov-action v2
package.json
consola ^2.15.3
defu ^5.0.0
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
https://codesandbox.io/s/vigilant-booth-27tv8?file=/pages/index.vue
Run a sandbox project
Call this.$router.push("/about"); in the component
Watch the returned value
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.
push is returning undefined.
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.