B02-国际化语言配置

news/2024/5/20 4:36:17 标签: vue, ts, pinia

🧑‍🎓 个人主页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🍑 【菜单中使用】

在这里插入图片描述

/**
* 菜单标题
* @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>

http://www.niftyadmin.cn/n/229996.html

相关文章

电脑有自带的录屏功能吗?电脑录屏如何录人脸

案例&#xff1a;所有电脑都有自带的录屏功能吗&#xff1f; “在网上了解到电脑有录屏功能&#xff0c;但是我在我的电脑上又找不到。想问问小伙伴们是所有的电脑都有自带的录屏功能吗&#xff1f;怎样才能找到电脑自带的录屏功能&#xff1f;” 在日常使用电脑时&#xff0…

ChatGPT实战100例 - (02) 自动出PPT它不香么?

文章目录ChatGPT实战100例 - (02) 自动出PPT它不香么&#xff1f;一、需求与思路1. 需求&#xff1a;出个PPT&#xff0c;5分钟后要用2. 思路&#xff1a;生成markdown然后转化二、生成markdown语法的思维导图1. 问题2. 回答三、把markdown文本转换成PPTChatGPT实战100例 - (02…

uniapp在安卓10+情况下移动文件的解决方案

uniapp在安卓10情况下移动文件的解决方案 首先看一个简单的问题&#xff0c;就是uniapp如何将下载的图片保存到手机本地&#xff0c;直接看下面的代码 const imgUrl https://fanyi-cdn.cdn.bcebos.com/static/translation/img/header/logo_e835568.pnglet dtask plus.downlo…

telegraf在iiot领域的基本应用(Modbus,OPC)

熟悉telegraf是因为influxdb缘故&#xff0c;当时telegraf主要是作为granfa监控的agent一环&#xff0c;很多文章有相关的介绍&#xff0c;但作为java开发对telegraf&#xff08;go语言开发&#xff09;也仅仅只是适用级别&#xff0c;这边文章也只讲到一些简单的应用。希望能帮…

开源自动化测试框架有哪些?怎么选择适合自己的

目录 前言 一、Selenium 二、Appium 三、Robot Framework 四、Cypress 五、TestCafe 六、Nightwatch.js 七、JUnit 八、Pytest 总结&#xff1a; 前言 开源自动化测试框架是现代软件开发和测试领域中不可或缺的一部分。它们使得测试人员能够快速、准确地执行测试用例…

收藏!7个国内「小众」的程序员社区

技术社区是大量开发者的集聚地&#xff0c;在技术社区可以了解到行业的最新进展&#xff0c;学习最前沿的技术&#xff0c;认识有相同爱好的朋友&#xff0c;在一起学习和交流。 国内知名的技术社区有CSDN、博客园、开源中国、51CTO&#xff0c;还有近两年火热的掘金&#xff…

CSS 23 知识点整理

CSS 层叠样式表&#xff08;Cascading Style Sheets&#xff09; 行内样式 写在标签的 style 属性中&#xff0c;又称内联样式 <h1 style"color:red"></h1>内部样式 写在 html 页面内部&#xff0c;将所有的 CSS 代码提取出来&#xff0c;单独放在 …

动态代理入门必看

基本介绍 代理 就是让代理角色帮助真实角色完成一件事情。比如说&#xff0c;我叫我们朋友帮我完成博客&#xff0c;那么这个朋友就是代理&#xff0c;朋友不是我&#xff0c;但是和我完成同样的事&#xff0c;并且还可以对这件事加入他的行为逻辑。 不论是什么代理方法&…