Search code examples
vuejs2vue-i18n

Combining Vue-i18n Single File Component syntax with root messages


I'm experimenting with the excellent vue-i18n plugin for Vue. It has a neat feature that allows me to embed translations directly into the template that needs them. However if I use them, I'm unable to access the root translation node. Is this model supported or am I just doing it wrong?

main.js

import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
const i18n = new VueI18n({
  locale: 'en',
  messages: {
    en: {
      'company-name': 'billy-bob\'s fine steaks.'
    }
  }
});

Sample.vue

<i18n>
  {
    "en": {
      "title": "@:company-name - yeee hawwww!!!"
    }
  }
</i18n>

<template>
  <div id="app" class="container">
    <site-header :title="$t('title')"></site-header>
  </div>
</template>

Solution

  • It appears that the i18n definitions are merged together so that, in the component, you would have access to both the parent and child i18n definitions, with the child definitions overriding the parents where there was any overlap (for example, if you had a title key in the parent and the child, the child's would be used).

    However the syntax you are using clearly doesn't work. In this case I think I would define a computed that combines the two translated values and use that.

    computed:{
        title(){
            return this.$t("company-name") + this.$t("title")
        }
    }
    

    And then just use the computed value in your template.

    <template>
      <div id="app" class="container">
        <site-header :title="title"></site-header>
      </div>
    </template>