在组件外使用 VueI18n 的问题

Problem to use VueI18n outside a component

我正在尝试在组件外部使用 i18n 我发现这个解决方案 https://github.com/dkfbasel/vuex-i18n/issues/16 告诉我要使用 Vue.i18n.translate('str'),但是当我调用它时会发生这种情况一个错误 Cannot read 属性 'translate' of undefined.

我正在使用以下配置

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
    }
}

然后我尝试使用这个

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

谁能帮帮我?

你应该导入 i18n 而不是 Vue

import i18n from './i18n'

i18n.tc('someMessage')

我设法让它以这种方式工作:

import router from '../router';

翻译一段文字:

let translatedMessage = router.app.$t('someMessage');

获取当前语言:

let language = router.app.$i18n.locale;

使用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。在具有可单元测试组合函数的文件中:

// 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

您可以通过导入 i18n 使用 VueI18n 外部组件,然后使用“t”来自 i18n.global.

"t" 不需要 "$" 并且您可以更改 Locale使用 i18n.global.locale.

import i18n from '../i18n';

const { t } = i18n.global;

i18n.global.locale = 'en-US'; // Change "Locale"

const data = { 
  name: t('name'), // "t" doesn't need "$"
  description: t('description'), // "t" doesn't need "$"
};