Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current locale in a child component

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()
})

like image 602
Seb Avatar asked Jan 29 '19 18:01

Seb


1 Answers

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

like image 73
Cesar Martinez Dominguez Avatar answered Nov 15 '22 07:11

Cesar Martinez Dominguez