I am currently using vueJS to make a front-end interface, and currently using vuejs 3 and i18n. The i18n implementation works fine in the normal way, but when I want to use it with the composition API, problems arise.
So what did I do. My main.js looks like this:
const i18n = createI18n({ messages: { en: en, fr: fr }, fallbackLocale: 'en', locale: localStorage.Language || navigator.language.split('-')[0] || 'en', }) const app = createApp(App) app.use(router) app.use(i18n) app.mount('#app')
I saw in the documentation that to use the composition API I had to add legacy:false, so I did that. Then my $t doesn't work anymore. I looked further into the documentation and got to where I was lost. The documentation says to use this:
const app = Vue.createApp({ setup() { const { t } = VueI18n.useI18n() // call `useI18n`, and spread `t` from `useI18n` returning return { t } // return render context that included `t` } })
My problem is that my createApp is already used like this:
const app = createApp(App)
This is the default implementation of Vuejs. I've tried modifying it, adding settings after the app, before, and deleting the app has no effect and I think I'm doing more and more stupid things.
Does anyone know how to get i18n to work with the composition API? The end goal is basically to use the component switchLanguage made with the composition API to access $i18n (get some information and manage my language switching)
Thanks in advance for any help.
You have instantiated
i18n
inmain.js
on your application. This is an important point.The examples provided in the documentation do not necessarily have to be completed on the instance defined in
createApp
. It works with any component as long as you instantiate i18n onmain. (js|ts)
This works for any component (however you need
t
):Side note: All
$tc
(pluralization) functionality has been moved tot
.If you are upgrading an existing application and do not want to go through templates and replace all instances of
$t
and$tc
witht
:To make
$t
and$tc
available in<template>
of any component, not necessarily in<script>
(or<script setup>
) to import and expose them:<script>
, import from'vue-i18n'
as shown above.$tc
is no longer used in Vue3. If your template comes from Vue2, it's a good idea to replace all$tc
with$t
. Alternatively, if you don't want to touch the template, you can assignuseI18n().t
to both: