12

I don't manage to get the locale parameter from vue-i18n in my child component.

I've installed vue-i18n in cli ui. The translation with $t("message") is working but I have error when i try to access to i18n.locale

my enter point (main.js)

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import i18n from './i18n'

    new Vue({
      router,
      i18n,
      render: h => h(App)
    }).$mount('#app')

my child component

<template>
    <div>{{ $t("message") }}</div>
</template>
<script>
import {HTTP} from '@/http-common'

export default 
{
  name : 'c1',
  methods:{
      selectMap()
      {
          console.log(i18n.locale);//=> doesn't work
      }
}
</script>

i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

function loadLocaleMessages () {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
  const messages = {}
  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i)
    if (matched && matched.length > 1) {
      const locale = matched[1]
      messages[locale] = locales(key)
    }
  })
  return messages
}

export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages()
})

Seb
  • 121
  • 1
  • 1
  • 4
  • 6
    should be `console.log(this.$i18n.locale)` http://kazupon.github.io/vue-i18n/api/#injected-properties – thanksd Jan 29 '19 at 18:11
  • I get this error `Cannot read property '$i18n' of undefined` – Seb Jan 29 '19 at 18:48
  • That means you are trying to access `this.$i18n` in a context where `this` is not the vue instance. If you're trying to access it in one of your child component's methods, this should not be the case. Your `methods` object in your child component example code doesn't have a closing bracket, though, and the component seems incomplete in general. So, I'm assuming you're not calling it from that context. – thanksd Jan 29 '19 at 18:58
  • you're right, I tried to simplify the code and didn't call this.$i18n in the right method. Now everything is working fine, thanks for your help! – Seb Jan 29 '19 at 19:09

2 Answers2

13

Try this.$i18n.locale, or just $i18n.locale if inside the <template>.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
3

For Composition API this is my solution:

<script setup>
    import { useI18n } from "vue-i18n";
    
    const i18nLocale = useI18n();
    console.log(i18nLocale.locale.value); // "en"
</script>
Esset
  • 916
  • 2
  • 15
  • 17
gnegis
  • 31
  • 3