在组件外使用 VueI18n 的问题

Ale*_*nen 3 vue.js vuejs2 vue-i18n

我正在尝试在组件之外使用 i18n 我发现这个解决方案https://github.com/dkfbasel/vuex-i18n/issues/16告诉使用 Vue.i18n.translate('str'),但是当我调用这会发生错误无法读取未定义的属性“翻译”。

我正在使用以下配置

主文件

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

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,
});
Run Code Online (Sandbox Code Playgroud)

i18nData.js

export default {
    en: {
        //my messages
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试使用这个

import Vue from 'vue';
Vue.i18n.translate('someMessage');
Run Code Online (Sandbox Code Playgroud)

谁能帮我?

itt*_*tus 9

你应该导入i18n而不是 Vue

import i18n from './i18n'

i18n.tc('someMessage')
Run Code Online (Sandbox Code Playgroud)


小智 8

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

t ”不需要“ $ ”,您可以使用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 "$"
};
Run Code Online (Sandbox Code Playgroud)


dtk*_*dtk 5

i18n与 Vue 3 的组合 API 一起使用,但在组件的 之外setup()您可以t在其global属性访问其翻译 API(例如函数)。

例如 在具有单元可测试组合函数的文件中:

// i18n/index.js

import { createI18n } from 'vue-i18n'
import en from './en.json'

  ...

export default createI18n({
  datetimeFormats: {en: {...}},
  locale: 'en',
  messages: { en }
})
Run Code Online (Sandbox Code Playgroud)
// 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
Run Code Online (Sandbox Code Playgroud)

  • 此示例**不**使用 vue-i18n 的组合 API 模式。为此,您需要 createI18n({legacy: false; }) (3认同)