如何在Vuex store中使用i18n



我有一个项目,我需要在Vuex商店内做翻译。但是当我试图在商店内使用i18n进行翻译时,我一直得到一个错误。

我尝试使用下面的import语句在store中导入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(),
});

对于那些在Vuex商店中挣扎着使用i18n的Vue 3家伙,我能够像这样实现它:

翻译/index.js with basic setup

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

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

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

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

我可以使用这个。$i18n in my store:

this.$i18n.t('campaign.setPhotodoc-error')

最新更新