简体   繁体   English

使用 vue i18n 在 Vue 中的道具上使用 t 翻译

[英]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.但是我假设因为我的字符串是通过道具传递的,所以它们没有像我的代码的 rest 那样被翻译。 Below you will find my current 2 components that I am working with:下面你会发现我目前正在使用的 2 个组件:

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.您的两种解决方案都应该像我们始终在全局级别配置VueI18n一样工作。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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