【问题标题】:How to change attribute lang html using vue-i18n如何使用 vue-i18n 更改属性 lang html
【发布时间】:2019-09-06 04:14:39
【问题描述】:

我想改变html元素的属性:

lang='en'

lang='jp'

当我使用包 vue-i18n 更改语言时。

我在nuxt.config.js中导入插件vue-i18n并添加属性:

 htmlAttrs: {
    lang: this.$i18n.locale,
 },

head 对象中,但它抛出错误:无法读取未定义的属性“$i18n”

这是我的 vue-i18n 插件:

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

Vue.use(VueI18n);

export default ({ app, store }) => {
    app.i18n = new VueI18n({
        locale: store.state.i18n.locale,
        fallbackLocale: 'vi',
        messages: {
            en: require('~/locales/en.json'),
            vi: require('~/locales/vi.json'),
            jp: require('~/locales/jp.json'),
        },
    });
};

感谢您的阅读!

【问题讨论】:

    标签: nuxt.js


    【解决方案1】:

    nuxt.config.js 文件的 i18n 配置部分,将 seo 属性设置为 true 并且 i18n 模块应负责为您设置 html lang 属性。

    i18n: {
       seo: true,
       ...
    }
    

    Nuxt i18n 文档:https://nuxt-community.github.io/nuxt-i18n/seo.html#benefits

    【讨论】:

    • 实际上,这个答案并没有回答 OP 的要求,而且这种方法只适用于 nuxt-i18n,它在 NPM 或 Yarn 中具有相同的名称。
    【解决方案2】:

    如果您考虑不在nuxt.config.js 中使用htmlAttrs,而是在其他文件中使用(例如,我在我唯一的布局中使用MainHeader.vue 中的htmlAttrs),那么这就是代码:

    export default {
      name: 'MainHeader',
      head() {
        return {
          meta: [{
            hid: 'og:locale', property: 'og:locale', content: this.currentLocaleDecoding
          }],
          htmlAttrs: {
            lang: this.currentLocale ? this.currentLocale : 'en'
          }
        }
      },
    ...
      computed: {
        currentLocale() {
          return this.$i18n.locale
        },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 2016-03-13
      • 2013-04-30
      相关资源
      最近更新 更多