I have the vueI18n package installed for language localization in the app and the locale messages object is fetched through an api call. I have config file where the default language is specified and based on which the locale will be loaded before the app.vue is created. ie; I'm loading the locale in beforeCreate lifecycle method. But still the text are not loaded properly.
Initially the message object is null because based on the user config we are fetching the language and loading the messages. I am assuming the initial empty object is causing the issue.
Could someone suggest a way we can delay the page load until we confirm the message object is loaded successfully.
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import userConfig from './userConfig'
import apiService from '@/service/apiService.js'
let selectedLanguage = ''
Vue.use(VueI18n)
const loadLocaleMessages = async (lang) => {
const messages = await apiService.getLocale(lang)
return messages
}
export const i18n = new VueI18n({
locale: selectedLanguage,
fallbackLocale: userConfig.defaultLocalizationKey,
formatFallbackMessages: true,
messages: {}
})
export const loadLanguage = async lang => {
const messages = await loadLocaleMessages(lang)
selectedLanguage = lang
return i18n.setLocaleMessage(selectedLanguage, messages[lang])
}
async beforeCreate () {
await loadLanguage(this.$userConfig.defaultLocalizationKey)
this.$i18n.locale = this.$userConfig.defaultLocalizationKey
}
The good practice is to always have a default/fallback language inside vue-i18n, e.g. English. If you can't do this for whatever reason, then you can simply put a v-if on the App's template so that nothing is rendered until you fetch at least 1 language into vue-i18n.