我正在使用 vue 并通过命令添加 i18n
vue add i18n
添加后。 i18n 无法从文件夹 locales
组件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 !!"
}
<p>{{ t('hello') }}</p>
有效,但 <p>{{ t('message') }}</p>
无效。
错误:[intlify] Not found 'message' key in 'en' locale messages.
答案 0 :(得分:3)
这 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