【问题标题】:vue i18n unable load translation from localesvue i18n 无法从语言环境加载翻译
【发布时间】:2023-04-07 22:42:01
【问题描述】:

我正在使用vue并通过命令添加i18n

vue add i18n

添加后。 i18n 无法从文件夹 locales 中的 json 文件加载

组件HelloI18n.vue

<template>
  <div>
    <p>{{ t('hello') }}</p>
    <p>{{ t('message') }}</p>
  </div>
</template>

<script>
// import { defineComponent } from 'vue'
import { useI18n } from 'vue-i18n'

export default ({
  name: 'HelloI18n',
  setup() {
    const { t } = useI18n({
      inheritLocale: true,
      useScope: 'local'
    })

    // Something todo ..

    return { t }
  }
})
</script>

<i18n>
{
  "en": {
    "hello": "Hello i18n in SFC!"
  }
}
</i18n>

src/locales/en.json

{
  "message": "hello i18n !!"
}

&lt;p&gt;{{ t('hello') }}&lt;/p&gt; 有效,但 &lt;p&gt;{{ t('message') }}&lt;/p&gt; 无效。

错误:[intlify] Not found 'message' key in 'en' locale messages.

我的回购地址:https://github.com/duyetvn/vue-i18n-sample

【问题讨论】:

    标签: vue.js internationalization


    【解决方案1】:

    这个line 是问题所在:

    function loadLocaleMessages() {
      const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
      const messages = {}
      locales.keys().forEach(key => {
        const matched = key.match(/([A-Za-z0-9-_]+)\./i)
        if (matched && matched.length > 1) {
          const locale = matched[1]
          messages[locale] = locales(key) ?
        }
      })
      return messages
    }
    

    locales(key) 加载模块,但数据存储在default 键内。解决方法是使用该密钥:

    messages[locale] = locales(key).default
    

    https://github.com/duyetvn/vue-i18n-sample/pull/1

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 1970-01-01
      • 2012-03-25
      • 2021-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多