how to write global router-function in nuxt.js
Solution 1
You can create a plugin for Nuxt
create a plugins/route.js
file:
export default ({ app }) => {
// Every time the route changes (fired on initialization too)
app.router.afterEach((to, from) => {
//do something to validate
})
}
and update your nuxt.config.js
file:
plugins: ['~/plugins/route']
More details about Nuxt plugins: https://nuxtjs.org/guide/plugins
Solution 2
If anybody might be still interested, it's possible to setup global middleware in nuxt.config.js
like this:
router: { middleware: ['foo'] },
then in your middleware/foo.js
you do whatever...
export default function({ route, from, store, redirect }) {}
Beware: You can't use this for static sites (nuxt generate), because middleware is not executed on page load, but only on subsequent route changes. Thanks @ProblemsOfSumit for pointing that out.
Jacky Wong
Updated on June 05, 2022Comments
-
Jacky Wong almost 2 years
I am using Vue.js with Nuxt.js, but I got a problem in router's functions.
In the pure Vue, i can write in
main.js
like this:val route = new Router({ routes:{ [...] } }) route.beforeEach(to,from,next){ //do something to validate }
And how to do the same in nuxt.js ? I can not find any file like
main.js
.Also, all i know is to deal with the
pages
folder to achieve router, I can not set the redirect pathplease help, thx :)
-
Pyae Sone over 5 years@JackyWong how do you do it with middleware?
-
Alireza almost 5 yearsI guess if you use SPA mode, you don't have middleware, right?
-
iSaumya over 4 yearsCan't thank you enough for this helpful snippet of code. I was trying to make a middleware for this
-
Schäbo over 4 yearsFor future reference: You can use middleware in SPA mode. For SPAs it is only executed on the client side. See this discussion on github for all the gotchas: github.com/nuxt/nuxt.js/issues/2653
-
ProblemsOfSumit about 4 yearsFor static sites, you can't use middleware because they are not executed on page load, only on subsequent route changes.
-
ProblemsOfSumit about 4 yearsIf you reload any of your routes directly, they are also not called
-
PirateApp over 2 yearswhat is the difference between a nuxt plugin and router middleware, from what I see they seem to do the exact same thing?
-
xpuu over 2 yearsPlugins have much broader scope of use as opposed to middlewares which are closely connected to routing.