Search code examples
javascriptnode.jsvue.jsvue-componentvue-i18n

Problem to use VueI18n outside a component


I'm trying to use i18n outside a component I've found this solution https://github.com/dkfbasel/vuex-i18n/issues/16 telling to use Vue.i18n.translate('str'), but when I call this occurs an error Cannot read property 'translate' of undefined.

I'm using the following configuration

main.js

import i18n from './i18n/i18n';
new Vue({
    router,
    store,
    i18n: i18n,
    render: h => h(App)
}).$mount('#app')

i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import i18nData from './i18nData'
Vue.use(VueI18n);
export default new VueI18n({
  locale: 'en',
  messages: i18nData,
});

i18nData.js

export default {
    en: {
        //my messages
    }
}

Then I trying to use this

import Vue from 'vue';
Vue.i18n.translate('someMessage');

Can anyone help me?


Solution

  • To use i18n with Vue 3's composition API, but outside a component's setup(), you can access its translation API (such as the t function) on its global property.

    E. g. in a file with unit-testable composition functions:

    // i18n/index.js
    
    import { createI18n } from 'vue-i18n'
    import en from './en.json'
    
      ...
    
    export default createI18n({
      datetimeFormats: {en: {...}},
      locale: 'en',
      messages: { en }
    })
    
    // features/utils.js
    
    //import { useI18n } from 'vue-i18n'
    //const { t } = useI18n() // Uncaught SyntaxError: Must be called at the top of a `setup` function
    
    import i18n from '../i18n'
    
    const { t } = i18n.global