如何让 Nuxt-auth 和 Nuxt-i18n 成为朋友

How to make Nuxt-auth and Nuxt-i18n to be friends

我想同时使用 nuxt@auth 模块和 nuxt-i18n。当我想为登录页面设置不同的路由时,就会出现问题。例如:

pages: {
 login: {
  en: '/authorization',
  fr: '/autorisation'
 }
}

路由运行良好,但是当我尝试在所有页面受限的情况下使用 nuxt@auth 时,默认重定向要求访问 /login 页面。在 nuxt.config.js 文件中我可以重写重定向路由,但我只能设置一个重定向。

auth: {
 redirect: {
  login: '/fr/autorisation'
 }
}

如何向授权模块显示以请求所选语言的路由?提前致谢!

似乎有解决该问题的方法 https://github.com/nuxt-community/auth-module/pull/185,但我无法访问当前版本中的 onRedirect 方法。

我做了一个解决方法。我添加了 auth-lang-redirect.js 插件,它覆盖了 nuxt.config.js 文件中定义的 redirect 选项。

export default ({ app }) => {
  var redirect = app.$auth.$storage.options.redirect
  for (var key in redirect) {
    redirect[key] = '/' + app.i18n.locale + redirect[key]
  }
  app.$auth.$storage.options.redirect = redirect
}

请注意,我没有使用 nuxt-i18n 模块,但您应该明白了。 您必须像这样在 nuxt.config.js 中注册此插件:

auth: {
    strategies: { ... },
    redirect: {
      login: '/login',
      logout: '/',
      callback: '/login',
      home: '/user/profile'
    },
    plugins: ['@/plugins/auth-lang-redirect.js']
  },

希望对大家有所帮助=)

export default ({ app, $auth }) => {
 $auth.onRedirect((to, from) => {
   return app.localePath(to)
  })
}
export default function({ app, $auth }) {
  const redirect = { ...$auth.$storage.options.redirect };

  const localizeRedirects = () => {
    for (const key in redirect) {
      $auth.$storage.options.redirect[key] = app.localePath(redirect[key]);
    }
  };

  localizeRedirects();

  app.i18n.onLanguageSwitched = () => {
    localizeRedirects();
  };
}