[英]Using t translation on props in Vue with vue i18n
我想翻譯通過道具傳遞給我的組件的標題。 但是我假設因為我的字符串是通過道具傳遞的,所以它們沒有像我的代碼的 rest 那樣被翻譯。 下面你會發現我目前正在使用的 2 個組件:
父組件:
`<setting-section
:title="$t('Random Text 1')"
:description="$t('Random Text 2')"
>`
在孩子身上:
`<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>`
如果我確實添加了以下變體,它顯然不會起作用。
`<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>`
您的兩種解決方案都應該像我們始終在全局級別配置VueI18n
一樣工作。 因此,翻譯文字總是可以從任何嵌套組件訪問。
根據這兩個用例進行現場演示:
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.