> 文章列表 > B02-国际化语言配置

B02-国际化语言配置

B02-国际化语言配置

🧑‍🎓 个人主页Silence Lamb
📖 本章内容:【国际化语言配置


Silence-Vitev 1.0.0

基于VITE前端快速开发框架

在这里插入图片描述

star star star star star


一、创建工具类

  • 🍖常用工具类src\\utils\\modules\\common.js
/*** @Description  : 常用工具类* @Author       : SilenceLamb* @Version      : V1.0.0*/
import {useSettingsStore} from '@/store/modules/settings';export default {/*** @Description 获取lang语言设置* @returns {string} 语言种类*/getLanguage() {const siteConfig = useSettingsStore();if (siteConfig) {return siteConfig.siteLanguage;} else {return 'zh';}},/*** @Description 设置语言种类* @param {string} lang 语言*/setLanguage(lang) {const siteConfig = useSettingsStore();siteConfig.siteLanguage = lang;},/*** @Description  : 设置网站标题* @param webTitle*/setSiteTitle(webTitle: string) {const siteConfig = useSettingsStore();useTitle().value = `${webTitle}${siteConfig.siteTitle ? ' 🌳 ' + siteConfig.siteTitle : ''}`;},/*** @Description 获取最后一个文件夹* @param {string} filePath* @returns {string} fileName 子文件夹名*/getLastFileName(filePath) {return filePath.substring(0, filePath.lastIndexOf('/')).split('/').pop();},/*** @Description 获取文件名* @param {string} filePath* @returns {string} fileName 文件名*/getFileName(filePath) {// 将路径拆分为数组const parts = filePath.split('/'),// 获取数组中的最后一个元素fileName = parts[parts.length - 1];// 获取文件名并返回return fileName.replace('.ts', '');},
};

二、语言切换组件

  • 🛞语言管理src\\components\\LangSelect
<!--* @Description  : 语言切换* @Author       : SilenceLamb* @Version      : V1.0.0
-->
<template><div><a-dropdown @click.prevent><svg-icon name="language" class="icon" /><template #overlay><a-menu @click="handleSetLanguage"><a-menu-item :disabled="language === 'zh'" key="zh">{{ $t('language.Chinese') }}</a-menu-item><a-menu-item :disabled="language === 'en'" key="en">{{ $t('language.English') }}</a-menu-item></a-menu></template></a-dropdown></div>
</template><script setup lang="ts">
import common from '@/utils/modules/common';
import { localeLading } from '@/language';
let { locale, messages } = useI18n();
const language = computed(() => {return common.getLanguage();
});/*** @Description    : 切换语言操作-只加载单个语言包* @param           {string} lang 语言种类*/
function handleSetLanguage({ key }) {common.setLanguage(key);const message = localeLading(key);messages.value[key] = message[key];locale.value = key;
}
</script>

三、国际化配置

3.1🌳【语言资源包】

  • 🌳中文src\\language\\modules\\utils\\zh\\index.js
/** @Description  : 国际化资源-中文* @Author       : SilenceLamb* @Version      : V1.0.0*/
export default {/*** @Description    : language.js*/language: {Chinese: '中文',English: '英文',},
}
  • 🌳英文src\\language\\modules\\utils\\en\\index.js
/** @Description  : 国际化资源-英文* @Author       : SilenceLamb* @Version      : V1.0.0*/
export default {/*** @Description    : language.js*/language: {Chinese: 'Chinese',English: 'English',},
}

3.2🌳【国际化配置】

  • 🌳加载语言资源src\\language\\index.js
/*** @Description  : 加载语言包* @Author       : SilenceLamb* @Version      : V1.0.0*/
import { createI18n } from 'vue-i18n';
import common from '@/utils/modules/common';
import antEnLocale from 'ant-design-vue/lib/locale/es_ES';
import antZHLocale from 'ant-design-vue/es/locale/zh_CN';/***  准备要合并的语言包* @type {{en: *[], "zh-cn": *[]}}*/
const assignLocale: any = {zh: [antZHLocale],en: [antEnLocale],
};
export let i18n: {global;
};
/*** @Description    : 加载在 modules 目录中动态加载语言包* @return          {{}} 语言源*/
export function localeLading(locale: string) {const messages = {zh: [],en: [],};const modulesFiles = import.meta.glob('./modules/**/**/*.ts', {eager: true,});for (const filePath in modulesFiles) {const localeMessage: any = modulesFiles[filePath].default;let fileName: String;fileName = common.getLastFileName(filePath);//合并语言包assignLocale[fileName].push(localeMessage);Object.assign(messages[locale], ...assignLocale[locale]);}return messages;
}
export default {install(app) {const locale = common.getLanguage();i18n = new createI18n({locale: locale,legacy: false, // 让 setup 函数可以通过 t 访问globalInjection: true, // 让 template 可以像 vue2 那样使用 $t 来访问fallbackFormat: 'en',messages: localeLading(locale),});app.use(i18n);},
};
  • 🌳全局引入src\\main.js
import { createApp } from 'vue'
import App from './App.vue'import i18n from '@/language' // 我是把i18n单独放一个文件夹,这里是引用const app = createApp(App)
app.use(i18n)app.config.productionTip = false // 阻止 vue 在启动时生成生产提示
app.mount('#app')

四、使用国际化

4.1🍑【组件中使用】

<template><div class="app-container">{{ t('language.Chinese') }}<a-button @click="getMessage">按钮</a-button></div>
</template>
<script setup lang="ts">const { t } = useI18n();
function getMessage(){console.log(t('language.Chinese'));
}
</script>

4.2🍑【JS文件使用】

    /*** @Description  : 根据系统时间获取问候语*/getGreet() {const now = new Date();const hour = now.getHours();let greet = '';if (hour < 5) {greet = i18n.global.t('common.Late at night');} else if (hour < 9) {greet = i18n.global.t('common.Good morning') + i18n.global.t('common.welcome back');} else if (hour < 12) {greet = i18n.global.t('common.Good morning') + i18n.global.t('common.welcome back');} else if (hour < 14) {greet = i18n.global.t('common.Good noon') + i18n.global.t('common.welcome back');} else if (hour < 18) {greet = i18n.global.t('common.Good afternoon') + i18n.global.t('common.welcome back');} else if (hour < 24) {greet = i18n.global.t('common.Good evening') + i18n.global.t('common.welcome back');} else {greet = i18n.global.t('common.Hello') + i18n.global.t('common.welcome back');}return greet;},

4.3🍑 【菜单中使用】

B02-国际化语言配置

/**
* 菜单标题
* @param title 标题
* @return {*} title |  this.$t(`router.` + title)
*/
routerTitle(title) {if (this.$t(`router.` + title)) {return this.$t(`router.` + title)} else {return title}
},

4.4🍑【手动切换语言】

<script setup lang="ts">
import common from '@/utils/modules/common';
import { localeLading } from '@/language';
let { locale, messages } = useI18n();
const language = computed(() => {return common.getLanguage();
});/*** @Description    : 切换语言操作-只加载单个语言包* @param           {string} lang 语言种类*/
function handleSetLanguage({ key }) {common.setLanguage(key);const message = localeLading(key);messages.value[key] = message[key];locale.value = key;
}
</script>