使用 i18n 和 Nuxt 时设置语言属性?

JMK*_*JMK 4 internationalization vue.js nuxt.js vue-i18n nuxt-i18n

使用 Nuxt,您可以在nuxt.config.js文件中设置语言 HTML 属性,如下所示:

module.exports = {
  head: {
    htmlAttrs: {
      lang: 'en-GB',
},
... etc etc
Run Code Online (Sandbox Code Playgroud)

但是,如果您有一个多语言应用程序,您应该怎么做?有没有办法根据语言环境设置语言属性?

我认为这可能document.documentElement.setSttribute('lang', 'language-code')会起作用,但是由于 nuxt 在服务器端呈现,它似乎无法访问 documentElement 对象。

谢谢

小智 8

也许我迟到了,但它就像你的这段代码一样简单layouts/default.vue

export default {
    // other code...
    head() {
        return {
            htmlAttrs: {
                lang: this.$i18n.locale
            }
        }
    },
    // other code...
}
Run Code Online (Sandbox Code Playgroud)


Sk_*_*Sk_ 2

  1. 安装 vue-i18n npm
 npm install vue-i18n
Run Code Online (Sandbox Code Playgroud)
  1. 在插件目录中创建一个插件并添加以下代码。例如:i18n.js
import Vue from 'vue' 

import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

export default ({app}) => {
    app.i18n = new ueI18n({
        locate: 'ja',
        fallbackLocale: 'en',
        silentTranslationWarn: true,
        message: {
            'ja': require('~/locale/ja/translations.json'),
             'en': require('~/locale/en/translations.json')
        }
    })
}
Run Code Online (Sandbox Code Playgroud)
  1. 将此插件包含在您的 nuxt.config.js 文件中并设置 lang
module.exports = {
    plugins: [{src: '~plugins/i18n.js', injectAs: 'i18n'}],
    head: {
        htmlAttrs: {
            lang: this.$i18n.locale,
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. Translations.json 文件包含 json 格式的翻译
{
    "hello": "Hello World"
}
Run Code Online (Sandbox Code Playgroud)
  1. 在组件文件中,您可以访问如下翻译
<p>{{ $t("hello") }}</p>
Run Code Online (Sandbox Code Playgroud)

注意:我没有测试代码