如何在 Vuex 商店中使用 i18n

use*_*338 3 javascript internationalization vue.js vue-i18n

我有一个项目需要在 Vuex 商店内进行翻译。但当我尝试在商店内使用 i18n 进行翻译时,我不断收到错误。

我尝试使用以下导入语句在商店内导入 i18n 实例。但我然后得到一个错误Uncaught TypeError: _i18n__WEBPACK_IMPORTED_MODULE_3__.default.t is not a function

import i18n from '@/i18n';
Run Code Online (Sandbox Code Playgroud)

在我的 Vue 项目的 main.js 文件中,我导入并使用 i18n 文件:

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { store } from './store';
import i18n from './i18n';

createApp(App).use(i18n).use(store).use(router).mount('#app');
Run Code Online (Sandbox Code Playgroud)

这是我的 i18n.js 文件,位于src文件夹内:

import { createI18n } from 'vue-i18n';

function loadLocaleMessages() {
  const locales = require.context(
    './locales',
    true,
    /[A-Za-z0-9-_,\s]+\.json$/i
  );
  const messages = {};
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  });
  return messages;
}

export default createI18n({
  legacy: false,
  locale: localStorage.locale ?? 'nl',
  globalInjection: true,
  messages: loadLocaleMessages(),
});
Run Code Online (Sandbox Code Playgroud)

equ*_*qui 7

对于在 Vuex 商店中努力使用 i18n 的 Vue 3 人员,我能够像这样实现它:

有基本设置的translations/index.js

import { createI18n } from 'vue-i18n'

const i18n = createI18n({
    fallbackLocale: 'en',
    globalInjection: true,
    messages: messages
})

export default i18n
Run Code Online (Sandbox Code Playgroud)

main.js 导入 store 和 i18n 并在 Vue 应用程序实例中使用它们

import i18n from './translations'
import store from './store'

const app = createApp(App)

app.use(store)
app.use(i18n)
app.mount('#app')
Run Code Online (Sandbox Code Playgroud)

Vuex 存储模块文件与 getter 示例:

import i18n from './translations'

const getters = {
  getNotification: (state) => {
      ...
      notification.title = i18n.global.t('notification.title')
      ...
  }
}
Run Code Online (Sandbox Code Playgroud)