具有 values 属性的 vue-i18n $t 未翻译

vue-i18n $t with values attribute is not translating

我正在尝试导入一个 .json 文件用作翻译文件。

<template>
    <template v-slot:footer>
      <div>{{ $t('menu.file.new.label', $i18n.locale, locale) }}</div> <--Issue outputs menu.file.new.label
    </template>
</template>

<script>
import locale from '@/locales/modules/messaging.json'

export default {
  data() {
    return {
      locale: locale
    }
  }
}
</script>

来自 messaging.json 的语言环境没有任何错误,如果我将以下内容添加到顶部

<i18n src="@/locales/modules/messaging.json"></i18n>

并更改函数参数以排除 $i18n.localelocale 并且它有效。不幸的是,这不是一个选项,因为我想将数据传递给孙子组件。但是,如果我可以将孙子配置为使用他们的祖父母翻译数据,那也可以..

我怎样才能得到:

  1. 以上工作
  2. 或者,使用孙子中祖父母的翻译数据
  3. 或者,根据prop(要导入的翻译文件的位置)动态导入孙子中的翻译数据

谢谢

首先,您应该创建一个如下所示的插件:

src/plugins/i18n.js:

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

const DEFAULT_LOCALE = 'en';

Vue.use(VueI18n);

const i18n = new VueI18n({
    locale: yourLocale || DEFAULT_LOCALE, // set locale either from localStorage or config
    fallbackLocale: DEFAULT_LOCALE,
    messages: require('messages.json'), // set locale messages
    sharedMessages: require('other.json if exist'),
    silentFallbackWarn: true,
});

export default i18n;

然后从main.js调用它进行全球化:

import i18n from './plugins/i18n.js';
...
new Vue({
    i18n,
    router,
...
    render: h => h(App),
}).$mount('#app');

然后如果你想继续自定义消息,你可以用 i18n 块设置它,比如:

<script>
data(){
...
}
methods: ...
i18n: {
 messages: require(your json path....)
}
</script>

然后你可以这样称呼它:

$t('test');

我找到了解决方案

<template>
  <st-age v-bind:menus="menu" v-bind:locale="locale[$i18n.locale].menu">
    <template v-slot:content>message: {{ $route.params }}</template>
    <template v-slot:footer>
      <div>{{ $t('menu.file.label') }}</div>
    </template>
  </st-age>
</template>

<script>
import menu from './menu'
import locale from '@/locales/modules/messaging.json'

export default {
  data() {
    return {
      menu: menu,
      locale: locale
    }
  },
  i18n: {
    messages: locale
  },
  components: {
    'st-age': () => import('@/components/layout/stage/container')
  }
}
</script>

<style>
</style>

locale[$i18n.locale].menu 正在传递我实际需要的翻译数据,而不是整个对象(这也有效)

在子组件中,我只是将此数据作为 prop 传递给孙组件

中孙i

 mounted() {
    this.$i18n.setLocaleMessage(this.$i18n.locale, this.locale)
  }

其中 this.locale 是翻译数据,$t('file') 生成我在最初导入的全局翻译数据中设置为 en.menu.file 的任何内容