下载npm包
npm install i18next i18next-vue i18next-browser-languagedetector
i18n.js文件
import i18next from 'i18next';
import { useLanguageStore } from '@/store/langStore';
const initI18n = (resources) => {
const languageStore = useLanguageStore();
const currentLang = languageStore.language || 'zh';
return i18next.init({
lng: currentLang,
fallbackLng: 'zh',
resources,
});
};
export { initI18n, i18next };
main.js
import i18next from "i18next";
import I18NextVue from "i18next-vue";
app.use(I18NextVue, { i18next })
pinia文件 langStore.js
import { defineStore } from 'pinia';
import i18next from 'i18next';
export const useLanguageStore = defineStore('language', {
state: () => ({
language: 'zh',
}),
actions: {
setLanguage(lang) {
this.language = lang;
i18next.changeLanguage(lang);
},
},
});
vue页面使用
import { initI18n, i18next } from '@/utils/i18n';
import { useLanguageStore } from '@/store/langStore';
watch(() => useLanguageStore().language, (newLang, oldLang) => {
console.log("newLang", newLang)
if (newLang !== oldLang) {
getCultureInfo();
}
}
);
const getCultureInfo = async () => {
const res = await getCulture()
console.log("res", res.data)
const resources = {
zh: {
translation: res.data.zh || {}
},
en: {
translation: res.data.en || {}
}
}
initI18n(resources)
let dataStore = i18next.getResourceBundle(i18next.language, 'translation')
注: 数据结构设计时 应返回对应的中英文数据字段 如返回数据结构为
{
en: {字段名,字段名},
zh: {字段名,字段名}
}
}