Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write global router-function in nuxt.js

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 path

please help, thx :)

like image 898
Jacky Wong Avatar asked Aug 04 '17 14:08

Jacky Wong


People also ask

What router does Nuxt use?

Nuxt automatically generates the vue-router configuration for you, based on your provided Vue files inside the pages directory. That means you never have to write a router config again!

How do I get the current route name in Nuxt?

Answer: Use the Vue. To get current route name from a URL in a Nuxt app that uses Vue Router you can use vue. js route objects like this. $route.name or this. $route.

Can I use vue3 with Nuxt?

It's only right that Nuxt 3 was built to support Vue 3 features. Vue 3 was released in October 2020 and has since garnered a lot of praise from the Vue community. With Nuxt 3 being written in Vue 3, you get access to features like the Composition API, better module imports, and overall improved app performance.


2 Answers

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

like image 64
Nicolas Pennec Avatar answered Oct 17 '22 18:10

Nicolas Pennec


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.

like image 38
xpuu Avatar answered Oct 17 '22 18:10

xpuu