search

Home  >  Q&A  >  body text

vuejs3 I18n and composition API

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.

P粉014218124P粉014218124241 days ago554

reply all(1)I'll reply

  • P粉237647645

    P粉2376476452024-03-26 11:42:48

    You have instantiated i18n in main.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 on main. (js|ts)

    This works for any component (however you need t):

    import { useI18n } from "vue-i18n";
    
    export default defineComponent({
      setup() {
        const { t } = useI18n();
        // you can now use t('some.text.to.be.translated')
        // t('some.text.to.be.pluralized', { n: 1 }, 1);
    
        return {
          // expose `t` to