【问题标题】:Setting the language attribute when using i18n and Nuxt?使用 i18n 和 Nuxt 时设置语言属性?
【发布时间】:2018-11-12 08:11:18
【问题描述】:

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

module.exports = {
  head: {
    htmlAttrs: {
      lang: 'en-GB',
},
... etc etc

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

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    如果您使用的是 nuxt-i18n,您可以在默认布局中使用 addSeoAttributes: true 调用 $nuxtI18nHead。这将设置 lang 属性以及其他一些特定于语言的标题属性,以实现更好的 SEO。

    export default {
        head() {
            return this.$nuxtI18nHead({ addSeoAttributes: true })   
        },
    }
    

    来源:https://i18n.nuxtjs.org/seo#improving-performance

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:
        1. 安装 vue-i18n npm
         npm install vue-i18n
        
        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')
                }
            })
        }
        
        1. 将此插件包含在您的 nuxt.config.js 文件中并设置语言
        module.exports = {
            plugins: [{src: '~plugins/i18n.js', injectAs: 'i18n'}],
            head: {
                htmlAttrs: {
                    lang: this.$i18n.locale,
                }
            }
        }
        
        1. translations.json 文件包含您的 json 格式翻译
        {
            "hello": "Hello World"
        }
        
        1. 在组件文件中,您可以访问如下翻译
        <p>{{ $t("hello") }}</p>
        

        注意:我没有测试代码

        【讨论】:

        • 谢谢,虽然我不认为这实际上设置了 标记中的 Language 属性。我问是因为这似乎对屏幕阅读器等很重要(Wave 将其显示为错误)。
        • 这不是 OP 要求的
        • 如何在 nuxt.config.js 中使用 this.$i18n?这对我不起作用。
        • 好的。您可以将 this.$i18n 用于 head,但 head 必须是返回对象的函数,而不仅仅是一个对象。
        • 正如@remino 之前所说,$i18n 无法通过nuxt.config.js 获得,因此答案不会按预期工作。
        猜你喜欢
        • 2020-06-20
        • 2019-08-06
        • 2015-03-24
        • 2018-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-05
        相关资源
        最近更新 更多