如何在nuxt.js中编写全局路由器函数

Jac*_*ong 7 vue.js vue-router nuxt.js

我正在使用Vue.js和Nuxt.js,但我在路由器的功能方面遇到了问题.

在纯Vue中,我可以这样写main.js:

val route = new Router({
   routes:{
      [...]
   }
})

route.beforeEach(to,from,next){
    //do something to validate
}
Run Code Online (Sandbox Code Playgroud)

以及如何在nuxt.js中做同样的事情?我找不到像这样的文件main.js.

另外,我所知道的是处理pages文件夹来实现路由器,我无法设置重定向路径

请帮忙,thx :)

Nic*_*nec 15

您可以为Nuxt创建一个插件

创建一个plugins/route.js文件:

export default ({ app }) => {
   // Every time the route changes (fired on initialization too)
   app.router.afterEach((to, from) => {
     //do something to validate
   }
}
Run Code Online (Sandbox Code Playgroud)

并更新您的nuxt.config.js文件:

plugins: ['~/plugins/route']
Run Code Online (Sandbox Code Playgroud)

有关Nuxt插件的更多详细信息:https://nuxtjs.org/guide/plugins


xpu*_*puu 5

如果有人可能仍然感兴趣,可以nuxt.config.js像这样设置全局中间件:

router: { middleware: ['foo'] },
Run Code Online (Sandbox Code Playgroud)

然后在middleware/foo.js你做任何事...

export default function({ route, from, store, redirect }) {}

Run Code Online (Sandbox Code Playgroud)

注意:您不能将它用于静态站点(nuxt generate),因为中间件不会在页面加载时执行,而只会在后续路由更改时执行。感谢@ProblemsOfSumit 指出这一点。