【问题标题】:Vue-Router and i18n with NuxtVue-Router 和 i18n 与 Nuxt
【发布时间】:2021-03-02 20:48:42
【问题描述】:

我正在将一个带有 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?

感谢您的帮助

【问题讨论】:

  • 路由器文件里为什么需要i18​​n?
  • 我想重定向到 /en/ 或 /de/ 等等,具体取决于浏览器语言。并设置语言环境。

标签: vue.js nuxt.js vue-router vue-i18n nuxt-i18n


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    它对我有用:

          {
            path: '/:lang([a-z]{0\,2})/blog/authors',
            component: AuthorsList
          },
    

    【讨论】:

      猜你喜欢
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 2019-10-27
      • 2018-05-15
      • 2019-02-21
      • 1970-01-01
      相关资源
      最近更新 更多