javascript - 在组件外使用 VueI18n 的问题

标签 javascript node.js vue.js vue-component vue-i18n

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

我正在使用以下配置

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');

谁能帮帮我?

最佳答案

使用i18n with Vue 3's composition API , 但在组件的 setup() 之外,you can access它的翻译 API(例如 t 函数)在其 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

关于javascript - 在组件外使用 VueI18n 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57049471/

相关文章:

vue.js - 从我的服务访问路由器实例

javascript - 对我生成的每个索引创建不同的 V-MODEL

javascript - 自制计算器不行

javascript - 避免循环内循环

node.js - 类型 'locals' 上不存在属性 'Response'

node.js - 带有 websocket 的 TTS :Creating a WAV from binary data fails

unity3d - 从统一 webGL 向 Vue js 发送消息

javascript - onclick 值中的空格会导致 HTML 不正确

javascript - 正文中的 POST 请求为 x-www-form-urlencoded

javascript - jQuery:为什么有人想要附加到一个封闭的列表元素?