vue-i18n, alternative for this.$i18n using the composition api?

Viewed 4540

trying to implement vue-i18n in a component with composition api. I want to be able to set some translation messages inside of the onMounted hook. In the options api, I would use this.$i18n.setLocaleMessage(locale, messages).

However, this is unavailable within the composition apis Setup() method. So it gives me undefined when I try the above. I can do it by importing i18n into the component: import { useI18n } from 'vue-i18n' and then make an instance of it var i18n = useI18n({}), i18n.setLocaleMessage(), but I would rather prefer the one line solution like the first one.

2 Answers

Just use t from useI18n as follows :

const {t} = useI18n({})
//then use in any place in the setup hook
onMounted(()=>console.log(t('someWord')) 

I had the same problem using the @vue/composition-api package with Vue 2. This setup requires vue-i18n v8.x, which doesn't have the useI18n composable.

I found luck creating a composable with my own useI18n function, modeled after this one from the creators of vue-i18n: https://github.com/intlify/vue-i18n-composable/blob/master/src/index.ts

Their solution is in TypeScript, so here's a translated JavaScript version in case it's useful for you:

/**
 * Adapted from https://github.com/intlify/vue-i18n-composable/tree/master/src
 * This is temporary to allow us to use VueI18n 8.x with the Composition API and Vue 2
 * Once we upgrade to Vue 3 (which allows an upgrade to VueI18n 9.x), we can remove this
 * in favor of VueI18n's useI18n() hook
 */

import { computed, getCurrentInstance } from '@vue/composition-api'
import Vue from 'vue'
import VueI18n from 'vue-i18n'

let i18nInstance = VueI18n

export function createI18n(options) {
  i18nInstance = new VueI18n(options)

  return i18nInstance
}

export function useI18n() {
  if (!i18nInstance) throw new Error('vue-i18n not initialized')

  const i18n = i18nInstance

  const instance = getCurrentInstance()
  const vm = instance?.proxy || instance || new Vue({})

  const locale = computed({
    get() {
      return i18n.locale
    },
    set(v) {
      i18n.locale = v
    }
  })

  return {
    locale,
    t: vm.$t.bind(vm),
    tc: vm.$tc.bind(vm),
    d: vm.$d.bind(vm),
    te: vm.$te.bind(vm),
    n: vm.$n.bind(vm)
  }
}

I saved that in src/composables/useI18n.js and use it in a Single File Component like so:

<template>
  <h1>{{ t('translate-me') }}</h1>
</template>


<script>
import { useI18n } from '@/composables/useI18n'

const i18n = {
  messages: {
    en: {
      : 'Finish Arranging Widgets',
    }
  }
}

export default {
  i18n,

  setup() {
    const { t } = useI18n()

    return { t }
  }
}
</script>
Related