[Vuejs]-Vue-i18n: language dependent view

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:

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>

Leave a comment