vue.jsvue-routernuxt.js

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 :)


Solution

  • It's possible to create a plugin for Nuxt that can add a global router function. This can be a useful way to extend the router capabilities of your Nuxt application.

    First, create a plugins/route.js file:

    // Nuxt <= 2.x
    export default ({ app }) => {
       // Every time the route changes (fired on initialization too)
       app.router.afterEach((to, from) => {
         //do something to validate
       })
    }
    

    or

    // Nuxt >= 3.x
    export default ({ app }) => {
       // Every time the route changes (fired on initialization too)
       app.$router.afterEach((to, from) => {
         //do something to validate
       })
    }
    

    Then update your nuxt.config.js file with:

    plugins: ['~/plugins/route']
    

    More details about plugins: