在vue-i18n中的子组件中使用基于组件的翻译

时间:2019-03-28 14:04:04

标签: vue.js vue-i18n

我正在使用vue-i18n在vue应用中翻译消息。我在new VueI18n(...)中添加了一些全局翻译,并在名为c-parent的组件中添加了一些基于组件的翻译。该组件包含名为c-child的子组件。现在,我想在c-parent中也使用c-child的基于组件的翻译。

我在这个小提琴中做了一个小例子:https://jsfiddle.net/d80o7mpL/

问题出在输出的最后一行:c-child中的消息未使用c-parent的基于组件的翻译来翻译。

由于全局翻译是所有组件“继承”的,因此我希望基于组件的翻译(在它们各自的组件子树中)具有相同的含义。是否可以在vue-i18n中实现这一目标?

2 个答案:

答案 0 :(得分:1)

好吧,您需要使用道具将文本传递给子组件。

所有组件都“继承”全局翻译。但是您在孩子中使用本地翻译。

const globalMessages = {
  en: { global: { title: 'Vue i18n: usage of component based translations' } }
}

const componentLocalMessages = {
	en: { local: {
    title: "I\'m a translated title",
    text: "I\'m a translated text"
  }}
}

Vue.component('c-parent', {
	i18n: {
  	messages: componentLocalMessages
  },
	template: `
    <div>
      <div>c-parent component based translation: {{ $t('local.title') }}</div>
      <c-child :text="$t('local.title')"></c-child>
    </div>
  `
})

Vue.component('c-child', {
  props: ['text'],
	template: `
		<div>c-child translation: {{ text }}</div>
	`
})

Vue.component('app', {
	template: '<c-parent />'
})

const i18n = new VueI18n({
	locale: 'en',
  messages: globalMessages
})

new Vue({
  i18n,
  el: "#app",
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

h5 {
  margin: 1em 0 .5em 0;
}
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-i18n"></script>

<div id="app">
  <h2>{{ $t('global.title') }}</h2>
  We define two Vue components: <code>&lt;c-child/&gt;</code> contained in <code>&lt;c-parent/&gt;</code>.
  <code>&lt;c-parent/&gt;</code> defines some component based translations. We would like to use the
  parent's translations in the child but it does not work.
  
  <h5>Example:</h5>
  <app />
</div>

答案 1 :(得分:0)

我正在做的是使用router.ts中的i18n.mergeLocaleMessage来合并特定的.i18n.json翻译文件(通过设置meta.i18n属性)对于每条路线

const router = new Router({
[...]
    {
      path: '/settings',
      name: 'settings',
      component: () => import('./views/Settings.vue'),
      meta: {
        i18n: require('./views/Settings.i18n.json'),
      },
    },
[...]
});

router.beforeEach((to, from, next) => {
    // load view-scoped translations?
    if (!!to.meta.i18n) {
      Object.keys(to.meta.i18n).forEach((lang) => i18n.mergeLocaleMessage(lang, to.meta.i18n[lang]));
    }
    next();
});

Settings.i18n.json如下:

{
    "en": 
    {
        "Key": "Key"    
    },
    "es": 
    {
        "Key": "Clave"    
    }
}

这样,所有子组件都将使用相同的翻译文件。

万一您不能使用vue-router,也许可以在父组件的mounted()钩子中进行(没有尝试过)

相关问题