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