如何在Vue中使用vue-i18n翻译props传递的组件标题?
问题
想翻译通过props传递给组件的标题,误以为props传递的字符串没法像代码里其他内容一样翻译。现有代码如下:
父组件代码
<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>
解决方案
方法1:保留父组件传递已翻译内容(推荐)
你最开始的写法其实是对的——父组件里用$t('翻译键')拿到翻译后的文本,再通过props传给子组件,子组件直接渲染{{ title }}就行。只要你的翻译文件里配置了对应的键值(比如'Random Text 1': '随机文本1'),就能正常显示翻译后的内容。
你后来试的写法问题出在:{{ $t('title') }}是把字符串'title'当成了翻译键,而不是读取props里的title值,自然找不到对应的翻译内容,所以显示英文(或者翻译键本身)。
方法2:子组件接收翻译键,内部做翻译
如果想让子组件负责翻译逻辑,可以改props为接收翻译键,而不是已经翻译好的文本:
修改后的子组件:
<template> <div class="flex grid w-full"> <div class="divider mr-4 mt-5" /> <div class="header col-2"> <div class="title text-primary">{{ $t(titleKey) }}</div> <div class="description text-xs">{{ $t(descriptionKey) }}</div> </div> <!-- 其余内容不变 --> </div> </template> <script> export default { name: 'Menu', props: { titleKey: { type: String, required: true, }, descriptionKey: { type: String, required: true, }, }, }; </script>
父组件调用方式:
<setting-section title-key="Random Text 1" description-key="Random Text 2" >
这种方式把翻译逻辑放在子组件,父组件只需要传翻译键就行。
方法3:子组件兼容两种模式(可选)
如果需要同时支持直接传文本和传翻译键的场景,可以在子组件里加判断:
<template> <div class="flex grid w-full"> <div class="divider mr-4 mt-5" /> <div class="header col-2"> <div class="title text-primary">{{ $i18n.te(title) ? $t(title) : title }}</div> <div class="description text-xs">{{ $i18n.te(description) ? $t(description) : description }}</div> </div> <!-- 其余内容不变 --> </div> </template> <script> export default { name: 'Menu', props: { title: { type: String, default: '', }, description: { type: String, default: '', }, }, }; </script>
这里用$i18n.te(key)判断当前键是否存在于翻译文件中,存在就翻译,不存在就直接显示传入的文本。
内容的提问来源于stack exchange,提问作者perrotss
相关产品推荐
相关产品推荐

