简体   繁体   中英

Using t translation on props in Vue with vue i18n

I would like to translate the titles that are passed to my component via props. However I assume because my strings are being passed via props they are not being translated like the rest of my code. Below you will find my current 2 components that I am working with:

Parent Component:

  `<setting-section
    :title="$t('Random Text 1')"
    :description="$t('Random Text 2')"
  >`

In the Child:

`<template>
  <div class="flex grid w-full">
    <div class="divider mr-4 mt-5" />
    <div class="header col-2">
      <div class="title text-primary">{{ title }}</div>
      <div class="description text-xs">{{ description }}</div>
    </div>
    <div class="flex col-10" v-if="!isLoading">
      <slot />
    </div>
    <div class="flex col-10" v-else>
      <Skeleton height="5rem" />
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Menu',
    props: {
      title: {
        type: String,
        default: '',
      },
      description: {
        type: String,
        default: '',
      },
    },
  };
</script>`

How ever if I do add the below variation it obviously wont work.

`<template>
  <div class="flex grid w-full">
    <div class="header col-2">
      <div class="title text-primary">{{ $t('title')}} </div>
      <div class="description text-xs">{{ description }}</div>
    </div>
  </div>
</template>`

Your both the solutions should work as we always configured VueI18n at global level. Hence, translation literals always accessible from any nested component.

Live Demo as per both the use cases :

 Vue.component('child-one', { props: ['childmsg'], template: '<p>{{ childmsg }}</p>' }); Vue.component('child-two', { template: `<p>{{ $t('message') }}</p>` }); Vue.use(VueI18n); const i18n = new VueI18n({ locale: 'ja', fallbackLocale: 'en', messages: { "ja": { "message": "こんにちは、世界" }, "en": { "message": "Hello World" } } }); new Vue({ el: "#app", i18n, data() { return { locale: "ja" } }, watch: { locale(newLocale) { this.$i18n.locale = newLocale; } } });
 <script src="https://cdn.jsdelivr.net/npm/vue@2.6.8/dist/vue.min.js"></script> <script src="https://unpkg.com/vue-i18n@8.8.2/dist/vue-i18n.min.js"></script> <main id="app"> <div> <label><input type="radio" value="ja" v-model="locale" />Japanese</label> <label><input type="radio" value="en" v-model="locale" />English</label> </div> <h3>Passing translated string from parent</h3> <child-one:childmsg="$t('message')"></child-one> <h3>Transaltions happens in child component itself</h3> <child-two></child-two> </main>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM