vue-i18n:依赖于语言的视图



我在应用程序中使用vue-i18n。现在我想添加一个";关于";带有大量文本和链接的视图。

我认为拥有几个依赖于语言的视图比在一个视图about.vue中添加几个{{ $t(...)}}更便于维护。

我想在视图名称中添加语言ISO代码:

  • /关于.en.vue
  • /关于.de.vue
  • /关于.es.vue

与vue-i18n组合和集成的最佳方式是什么?也许还有别的办法?

您可以使用动态组件来实现这一点:

<template>
<component :is="localizedAbout" />
</template>
<script>
import AboutEn from '../about.en.vue';
import AboutEs from '../about.es.vue';
import AboutDe from '../about.de.vue';
export default {
components: {
AboutEn,
AboutEs,
AboutDe,
},
computed: {
localizedAbout() {
switch (this.$i18n.locale) {
case 'en':
return AboutEn;
case 'es':
return AboutEs;
case 'de':
return AboutDe;
default:
return '';
}
},
},
}
</script>

在做了一些其他工作之后,我今天能够通过使用动态导入来解决这个问题:


<template>
<b-container class="about">
<component :is="langComponent" />
</b-container>
</template>
<script>

export default {
name: 'AboutView',
data () {
return {
langComponent: null
}
},
mounted () {
this.$watch(
'$i18n.locale',
(newLocale, oldLocale) => {
if (newLocale === oldLocale) {
return
}
this.setLangAbout()
},
{
immediate: true
}
)
},
methods: {
setLangAbout () {
try {
import('@/components/about/About.' + this.$i18n.locale + '.vue').then(module => {
this.langComponent = module.default
})
} catch (err) {
console.log(err)
import('@/components/about/About.en.vue').then(module => {
this.langComponent = module.default
})
}
}
}
}
</script>

感谢@Pochwar的初步回答。基于此,我做了更多的研究。以下链接帮助我解决了这个问题:

  • 与表达式一起使用时,webpack中的动态导入是如何工作的
  • 错误注释:找不到具有动态导入的模块

最新更新