簡體   English   中英

如何在 Vuex 商店中使用 i18n

[英]How to use i18n in the Vuex store

我有一個項目需要在 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');

這是位於src文件夾內的 i18n.js 文件:

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(),
});

我在 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";

然后在任何你想要的地方使用它(動作、突變、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!",

  }
};

對於那些在 Vuex 商店中苦苦使用 i18n 的 Vue 3 人來說,我能夠像這樣實現它:

帶有基本設置的翻譯/index.js

 import { createI18n } from 'vue-i18n' const i18n = createI18n({ fallbackLocale: 'en', globalInjection: true, messages: messages }) export default i18n

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')
帶有 getter 示例的 Vuex 存儲模塊文件:

 import i18n from './translations' const getters = { getNotification: (state) => {... notification.title = i18n.global.t('notification.title')... } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM