【问题标题】:How to use i18n in the Vuex store如何在 Vuex 商店中使用 i18n
【发布时间】:2021-08-31 14:56:16
【问题描述】:

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

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

import i18n from '@/i18n';

在我的 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');

这是我的 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(),
});

【问题讨论】:

    标签: javascript vue.js internationalization vue-i18n


    【解决方案1】:

    我在 Vuex 中使用了 vue-i18n。也许对你有帮助。

    像这样创建 vue-i18n.js 文件;

    import Vue from "vue";
    import VueI18n from "vue-i18n";
    
    // Localisation language list
    import { locale as en } from "@/core/config/i18n/en.js";
    import { locale as ch } from "@/core/config/i18n/ch.js";
    
    
    Vue.use(VueI18n);
    
    let messages = {};
    messages = { ...messages, en, ch };
    
    // get current selected language
    const lang = localStorage.getItem("language") || "en";
    
    // Create VueI18n instance with options
    const i18n = new VueI18n({
      locale: lang, // set locale
      messages // set locale messages
    });
    
    export default i18n;
    

    并在main.js文件中导入Vue;

    import i18n from "@/core/plugins/vue-i18n";
    
    new Vue({
      router,
      store,
      i18n,
      render: h => h(App),
    }).$mount('#app')
    

    将其导入您的商店或模块中(我在我的 vuex 模块中导入);

    import i18n from "@/core/plugins/vue-i18n";
    

    然后在任何你想要的地方使用它(action、mutation、setter 或 getter);

    const sample = i18n.t('ERRORS.NETWORKERROR');
    

    en.js 文件;

    export const locale = {
      LOGIN: {
        OPERATORID: "Operator ID",
        SIGNIN:"Sign In",
        SCANCARD: "Scan Card"
      },
      ERRORS: {
        NETWORKERROR: "Network error occurred!",
        UNAUTHUSERERROR: "Unauthorized user!",
    
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2021-07-22
      • 2017-12-18
      • 2019-04-28
      • 2020-01-10
      相关资源
      最近更新 更多