Dennis
Dennis

Reputation: 5

Vue3 vue-i18n Lazy loading

I would like to implement lazy loading for individual languages in my APP, however I don't really understand the example. Example: https://vue-i18n.intlify.dev/guide/advanced/lazy.html

i18n.js

import { nextTick } from 'vue'
import { createI18n } from 'vue-i18n'

export const SUPPORT_LOCALES = ['de', 'en']

export function setupI18n(options = { locale: 'de' }) {
  const i18n = createI18n(options)
  setI18nLanguage(i18n, options.locale)
  return i18n
}

export function setI18nLanguage(i18n, locale) {
  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale
  } else {
    i18n.global.locale.value = locale
  }
  document.querySelector('html').setAttribute('lang', locale)
}

export async function loadLocaleMessages(i18n, locale) {
  // load locale messages with dynamic import
  const messages = await import(
    /* webpackChunkName: "locale-[request]" */ `./locales    /${locale}.json`
  )

  // set locale and locale message
  i18n.global.setLocaleMessage(locale, messages.default)

  return nextTick()
}

My folder structure looks quite similar. I don't use the composition API at this point.

Instead of loading the languages via vue-router I would like to define a default language which can be changed in the user settings.

Where and how do I have to load the function "loadLocaleMessages()" now?

Currently I load the configuration in my main.js like this so that I have "$t" available in the template:

import { setupI18n } from "@/plugins/i18n";
...
app.use(setupI18n());
...

The i18n.js looks like in the example only that my path for the languages is different.

Also I would like to know how I have to include everything so that I have e.g. "$t" also available in other (not components)? E.g. in the routes.js or in the store (vuex)

EDIT: middlewares.js - beforeEachHook

import { i18n } from "@/plugins/i18n"
const { t } = i18n.global

/**
 * Translate/set page title
 */
export function setPageTitleMiddleware (to, from, next) {
    const pageTitle = to.matched.find(item => item.meta.title)

    if (to.meta && to.meta.title)
        window.document.title = process.env.VUE_APP_DOMAIN_TITLE + ' | ' + t(to.meta.title)
    else if
        (pageTitle && pageTitle.meta) window.document.title = process.env.VUE_APP_DOMAIN_TITLE + ' | ' + t(pageTitle.meta.title)

    next()
}

Upvotes: 0

Views: 1510

Answers (1)

Kylian Lion
Kylian Lion

Reputation: 21

To be able to get i18n translation from anywhere in your application (vue3 in my case) :

import i18n from "@/i18n";

i18n.global.t("your_key")

Upvotes: 0

Related Questions