npm install element-plus --save-dev
npm install pinia --save-dev
npm install vue-i18n --save-dev
npm install js-cookie --save-dev
2.在store中创建language.ts等此处的enLocal与zhLocal为对应的国际化ts文件,请自己定义
import Cookies from 'js-cookie';
import { createI18n } from 'vue-i18n';
import elementEnLocale from 'element-plus/lib/locale/lang/en';
import elementZhLocale from 'element-plus/lib/locale/lang/zh-cn';
import enLocale from './lang/en';
import zhLocale from './lang/zh-cn';
const langKey = 'i18nLang-key';
const messages = {
'en': {
...enLocale,
...elementEnLocale,
},
'zh': {
...zhLocale,
...elementZhLocale,
}
};
export const getCurrentLanguage = () => {
return Cookies.get(langKey);
};
export const setCurrentLanguage = (lang: string) => {
return Cookies.set(langKey, lang);
};
export const getLocale = () => {
const cookieLanguage = getCurrentLanguage();
if (cookieLanguage) {
return cookieLanguage;
}
const language = navigator.language.toLowerCase();
const locales = Object.keys(messages);
for (const locale of locales) {
if (language.indexOf(locale) > -1) {
return locale;
}
}
return 'zh';
};
const i18n = createI18n({
locale: getLocale(),
messages: messages
});
export default i18n;
下边的ts请自行创建,自行修改引入的路径即可
import { defineStore } from 'pinia';
import { getCurrentLanguage, setCurrentLanguage } from '@/assets/language';
const useLanguage = defineStore({
id: 'language-pinia',
state: () => ({
language: {}
}),
getters: {
getLanguage(): string {
this.language = getCurrentLanguage() + "";
return this.language;
}
},
actions: {
setLanguage(str: string) {
this.language = str;
setCurrentLanguage(this.language);
}
}
});
export default useLanguage;
3.在main.ts中注册element-plus并且配置国际化
import App from './App.vue';
import { createApp } from 'vue';
import elementPlus from 'element-plus';
// 引入国际化
import i18n from './assets/language/index';
const app = createApp(App);
// 设置element-plus国际化
app.use(i18n).use(elementPlus, {i18n: i18n.global.t });
4.增加切换国际化语言功能
中文
English
4.ts及页面使用
ts中使用需要先引入再定义,使用t('xxx.xxx')即可获取国际化信息
import { useI18n } from 'vue-i18n';
export default () => {
const { t } = useI18n();
let importDataBtnText = ref(t('button.import'));
}
对用的国际化定义ts
vue页面使用——$t('xxx.xxx')即可
5.测试国际化是否生效
注意:虽然这里切换语言成功,但是element-plus的分页组件并没跟着切换语言,而是需要F5刷新页面才行。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)