vue-i18n (版本号^9.1.9)
官网地址`https://vue-i18n.intlify.dev/guide/migration/breaking.html#apis`
## 第一步下载依赖 npm install vue-i18n@9
## 第二步创建中英文文件如下图
// src/lang/index.ts自定义国际化配置
import { createI18n } from 'vue-i18n';
import { localStorage } from '@/utils/storage';
// 本地语言包
import enLocale from './en';
import zhCnLocale from './zh-cn';
const messages = {
'zh-cn': {
...zhCnLocale,
},
en: {
...enLocale,
},
};
/**
* 获取当前系统使用语言字符串
*
* @returns zh-cn|en ...
*/
export const getLanguage = () => {
// 本地缓存获取
let language = localStorage.get('language');
if (language) {
return language;
}
// 浏览器使用语言
language = navigator.language.toLowerCase();
const locales = Object.keys(messages);
for (const locale of locales) {
if (language.indexOf(locale) > -1) {
return locale;
}
}
return 'zh-cn';
};
const i18n = createI18n({
legacy: false,
locale: getLanguage(),//当前使用语言
messages: messages,
});
export default i18n;
//zh-cn.ts
export default {
// 路由国际化
route: {
dashboard: '首页',
},
};
//en.ts
export default {
// 路由国际化
route: {
dashboard: 'Dashboard',
},
};
## 第三步 在main.ts中引入并挂载
//main.ts引入
import { createApp, Directive } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';
// 国际化
import i18n from '@/lang/index';
const app = createApp(App);
// 注册全局组件
app
.use(createPinia())
.use(i18n)
.mount('#app');
//App.vue
<template>
<el-config-provider :locale="locale" :size="size">
<RouterView />
el-config-provider>
template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { ElConfigProvider } from 'element-plus';
import useStore from '@/store';
// 导入 Element Plus 语言包
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import en from 'element-plus/es/locale/lang/en';
const { app } = useStore();
const language = computed(() => app.language);
const size: any = computed(() => app.size);
const locale = ref();
watch(
language,
value => {
locale.value = value == 'en' ? en : zhCn;
},
{
// 初始化立即执行
immediate: true,
},
);
script>
## 第五步页面中使用
<el-button type="primary" @click="UpdatBottomDialog">{{$t('options.update')}}el-button>
//模块中英文配置
公共封装@/hooks/useLang
import { useI18n } from "vue-i18n";
import useStore from "@/store";
import {computed} from "vue";
export default function useLang(messages: object) {
const { app } = useStore();
const locale = computed(() => app.language);
const { t } = useI18n({
locale: locale.value,
messages: { ...messages }
})
return { t, locale };
}
//中英文编写文件@/views/group/chart/index.t
export default {
en: {keep_Raw_Data: 'keep Raw Data'},
'zh-cn': {keep_Raw_Data: '保留原始数据'}
}
页面中使用
import chart from '@/views/group/chart/index.t';
import useLang from '@/hooks/useLang';
const { t } = useLang({ ...chart });
<el-table-column :label="t('keepRawData')"/>