how to write global router-function in nuxt.js

做~自己de王妃 提交于 2020-08-21 06:11:43

问题


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


回答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




回答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.



来源:https://stackoverflow.com/questions/45509472/how-to-write-global-router-function-in-nuxt-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!