0

I use vue-i18n in my application. Now I would like to add an "About" view with a lot text and links.

I think it would be better maintainable to have several language dependent views than adding several {{ $t(...)}} in one view about.vue.

I thought about something like adding language ISO code to the view name:

  • .../about.en.vue
  • .../about.de.vue
  • .../about.es.vue

What would be the best way to combine and integrate with vue-i18n? Probably there is a different way?

stritti
  • 51
  • 5

2 Answers2

0

You can use a dynamic component to achieve this:

<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>
Pochwar
  • 646
  • 5
  • 15
  • Hi @Pochwar, yes that is a great idea I totally forgot: dynamic components. I will try to do it a little more generic moving imports also within the method. Will see it it will work. – stritti Dec 08 '21 at 15:56
  • I never tried dynamic imports, let me know if it works ;) – Pochwar Dec 08 '21 at 16:04
0

After doing some other stuff, I was today able to solve this issue by using dynamic imports:


    <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>

Thanks @Pochwar for your initial answer. Based on this I have done some more researched. Following links helped me to solve this problem:

stritti
  • 51
  • 5