1

我正在将一个带有 vue-router 的项目从 Vue.js 转移到 Nuxt.js。

经过数小时的尝试和谷歌搜索,我设法让一切正常工作,但这是我无法工作的一个问题:**将 i18n 和 vue-router 与 Nuxt.js 集成 **

两个我还没有解决的问题:

  1. 如何在我的 router.js 文件中正确更新 i18n.locale?
  2. 如何告诉 nuxt-i18n 我正在使用自己的路由器?它现在显然抱怨Route with name 'XXX___en' does not exist.

在我的普通 vue 项目中,以下代码有效,我可以更改 router.js 中的语言环境,它会传播和更新 this.$i18n。

i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'

import termsHTML from './translations/terms'
import privacyHTML from './translations/privacy'
import imprintHTML from './translations/imprint'

Vue.use(VueI18n)

export const i18n = new VueI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages: { ... }
}

路由器.js

...
import {
  i18n
} from "@/plugins/i18n.js";
...
router.beforeEach((to, from, next) => {
// Set locale to new language
// I CANT GET THIS NEXT LINE WORING IN NUXT.JS
if (i18n.locale !== lang) i18n.locale = lang
...
}

现在在 Nuxt,我也想做同样的事情。我在 nuxt.config.js 中像这样导入了 nuxt-i18n 插件:

['nuxt-i18n', {
  seo: true,
  locales: [{
    code: 'en',
    name: '',
    iso: 'en-US'
  },
  {
    code: 'de',
    name: '',
    iso: 'de-DE'
  }],
  defaultLocale: 'en',
  vueI18n: {
    locale: 'en',
    fallbackLocale: 'en',
    messages: translations
  }
}],

我在路由器中尝试了以下操作但没有成功。

路由器.js

import nuxtConfig from "~/nuxt.config";
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// access the i18n module which is the second item in the modules array
// then take second item which is the config object and take the vueI18n property
let i18n = nuxtConfig.modules[1][1].vueI18n
...
if (i18n.locale !== lang) i18n.locale = lang

这不会出错,但也不起作用。Vue.use() 在这里可能是错误的,因为它注册了一个新组件,我猜我的代码没有引用正确的 i18n?

谢谢你的帮助

4

2 回答 2

0

这个对我有用:

      {
        path: '/:lang([a-z]{0\,2})/blog/authors',
        component: AuthorsList
      },
于 2021-10-08T07:44:43.647 回答
0

我现在得到了我想要的东西,不是在路由器文件中而是在始终加载的 NavBar.vue 组件中进行重定向。在那里你可以毫无问题地访问 this.$i18n。

于 2020-11-25T10:49:03.297 回答