【问题标题】:Problem to use VueI18n outside a component在组件外使用 VueI18n 的问题
【发布时间】:2019-07-16 02:59:50
【问题描述】:

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

我正在使用以下配置

ma​​in.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');

谁能帮帮我?

【问题讨论】:

  • 像这样使用 Vue.$i18n.translate() 相同的错误。无法读取未定义的属性“翻译”

标签: javascript vue.js vuejs2 vue-component vue-i18n


【解决方案1】:

要使用i18n with Vue 3's composition API,但在组件的setup() 之外,you can access 在其global property 上的翻译API(例如t 函数)。

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

【讨论】:

  • 这个例子使用 vue-i18n 的组合 API 模式。为此,您需要 createI18n({ legacy: false; })
  • @gagarine 您是否仅对初始化发表评论?你能提供更好的例子吗?
【解决方案2】:

你应该导入 i18n 而不是 Vue

import i18n from './i18n'

i18n.tc('someMessage')

【讨论】:

  • 这行得通,但是如果语言发生了变化,我需要在 VueI18n 的实例上应用,对吧?
  • 如果你的组件是响应式的,它会自动应用。
  • 谢谢,我从 Vue 开始,在这种情况下我需要做什么才能使组件反应?
  • 视情况而定。大多数时候,我通过使用 i18n.locale = 'en'(或 Vue 组件中的 this.$i18n.locale = 'en')来更改语言环境。它应该可以工作。
  • 谢谢,我试试这个。
【解决方案3】:

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

t”不需要“$”,您可以使用i18n.global.locale更改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 "$"
};

【讨论】:

    【解决方案4】:

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

    import router from '../router';
    

    翻译一段文字:

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

    获取当前语言:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 2023-01-19
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多