B02-国际化语言配置

news2024/10/5 2:24:13

🧑‍🎓 个人主页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.coloradmin.cn/o/418600.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

JavaScript(WebAPI)+具体案例

专栏简介: 前端从入门到进阶 题目来源: leetcode,牛客,剑指offer. 创作目标: 记录学习JavaEE学习历程 希望在提升自己的同时,帮助他人,,与大家一起共同进步,互相成长. 学历代表过去,能力代表现在,学习能力代表未来! 目录: 1. WebAPI 背景知识 1.1 什么是 WebAPI 1.2 DOM 基…

2023MathorCup数模D题思路数据代码论文【全网最全分享】

文章目录赛题思路赛题详情参赛建议&#xff08;个人见解&#xff09;选择队友及任务分配问题&#xff08;重要程度&#xff1a;5星&#xff09;2023MathorCup数模D题思路数据论文代码【最新】赛题思路 (赛题出来以后第一时间在CSDN分享) 最新进度在文章最下方卡片&#xff0c;…

GitLab集成阿里规约进行代码质量检查

1. 获取P3C-PMD (1) 下载源码 源码地址:https://github.com/alibaba/p3c (2) 打包 (3) 把打好的包(p3c-pmd-2.1.1-jar-with-dependencies.jar)拷贝到gitlab hooks脚本可以引用到的路径下,比如我这里拷贝到gitlab的安装目录下:/var/opt/gitlab/git-hooks(我的git…

Hyperledger Fabric项目搭建区块链浏览器Hyperledger-blockchain-explorer

Hyperledger Fabric项目搭建区块链浏览器 1.下载配置文件 区块链浏览器官网&#xff1a;https://github.com/hyperledger/blockchain-explorer # 根据官网来部署 # 在项目目录创建文件夹 # org1部署区块浏览器 mkdir explorer cd explorer # 下载配置文件 wget https://raw.…

软件测试分享15个适合练手的项目【金融/银行/商城/电商/医药......】

还愁没有练手的项目&#xff1f;我已经给你准备好了&#xff0c;需要评论区留下你的想法吧 1、引言 1.1 文档版本 版本 作者 审批 备注 V1.0 XXXX 创建测试方案文档 1.2 项目情况 项目名称 XXX 项目版本 V1.0 项目经理 XX 测试人员 XXXXX&#xff0c;XX…

【游戏开发】自从遇见了口袋方舟后,我的世界变得精彩了起来

文章目录前言口袋方舟编辑器口袋方舟训练营第一款游戏&#xff1a;四季跑酷第二款游戏&#xff1a;梦境逃脱个人感受其他说起游戏开发&#xff0c;我不允许还有人不知道口袋方舟编辑器&#xff01;前言 一直想写一篇博客来感谢口袋方舟&#xff0c;同时记录自己第一次游戏开发…

Centos7上配置python环境

Centos7上配置python环境1 安装包准备2 pycharm安装3 Anaconda安装4 pycharm配置解释器5 更改pip源1 安装包准备 pycharm下载&#xff1a;jetbrains官网 Anaconda下载&#xff1a; 清华大学开源软件镜像站 2 pycharm安装 下载好的pycharm软件包 2. 在 opt 文件夹下新建 soft…

卫星物联网的发展背景、研究现状、以及未来前景

今天这篇文章&#xff0c;我们来聊聊卫星物联网。 请大家注意&#xff0c;我说的是“物联网”&#xff0c;而不是“互联网”。 物联网&#xff0c;Internet of Things 众所周知&#xff0c;按使用对象&#xff0c;互联网可以分为“人联网”和“物联网”。我们普通消费者用户使…

Linux Shell 实现一键部署Nginx

nginx前言 nginx [engine x] 是 HTTP 和反向代理服务器、邮件代理服务器和通用 TCP/UDP 代理服务器&#xff0c;最初由Igor Sysoev编写。很长一段时间以来&#xff0c;它一直在许多负载重的俄罗斯网站上运行&#xff0c;包括 Yandex、 Mail.Ru、 VK和 Rambler。根据 Netcraft …

资本/车企持续加码的新赛道,谁将成为本土赢家?

随着汽车行业逐渐复苏&#xff0c;汽车厂商开始规划未来5年能促进销量的新技术&#xff0c;而AR-HUD就是被看好的技术之一。 Envisics创始人兼CEO Jamieson Christmas博士表示&#xff1a;我们几乎在与所有人合作&#xff0c;除了捷豹路虎、松下汽车系统外还有其他合作伙伴。此…

说走就走的旅行?你需要一个旅行必备清单

可能很多朋友都不用清单这个东西&#xff0c;更别说清单模版了。那清单真的好用吗&#xff1f;说实话&#xff0c;当你真的用清单来整理自己的日常工作&#xff0c;乃至生活琐事后&#xff0c;你就会发现你的时间多了&#xff0c;想要完成的事&#xff0c;大部分都可以按时完成…

Mysql 学习(四)InnDB 存储引擎-B+树索引

没有索引的查找 上节我们知道了数据是怎么存储的&#xff0c;数据被分成一个个页&#xff0c;然后页与页之间是根据双向列表来进行连接的&#xff0c;页中的记录是根据单向列表来进行连接的&#xff0c;并且将主键生成页目录。根据这个规则我们查找对应的记录数据&#xff0c;…

责任链设计模式

模拟学生请假流程&#xff0c;用以说明责任链模式。 请假天数 < 10&#xff0c;老师审批&#xff1b; 10 < 请假天数 < 20&#xff0c;主任审批&#xff1b; 20 < 请假天数 < 30&#xff0c;校长审批&#xff1b; 请假天数 > 30&#xff0c;超出学校允许请假…

vulnhub Hackathon2渗透笔记

靶机下载地址&#xff1a;https://www.vulnhub.com/entry/hackathonctf-2,714/ kali ip地址&#xff1a;192.168.20.130 信息收集 扫描靶机ip地址 nmap -sP 192.168.20.0/24确定靶机ip 进行端口扫描 nmap -A -p 1-65535 192.168.20.134首先我们使用匿名用户登录ftp看看有…

Graph Transformer系列论文阅读

文章目录research1.《Do Transformers Really Perform Bad for Graph Representation》【NeurIPS 2021 Poster】2.《Relational Attention: Generalizing Transformers for Graph-Structured Tasks》【ICLR2023-spotlight】survey推荐一个汇总Graph Transformer论文的项目&…

SpringMVC事务控制(xml文件配置和注解配置)

事务的定义 事务应该具有4个属性&#xff1a;原子性、一致性、隔离性、持久性。这四个属性通常称为ACID特性。 原子性&#xff08;atomicity&#xff09;。一个事务是一个不可分割的工作单位&#xff0c;事务中包括的操作要么都做&#xff0c;要么都不做。 一致性&#xff08;c…

实用的生产管理系统案例分析:如何应对市场快速变化?

生产管理系统是一种可视化管理工具&#xff0c;通过展示关键生产数据来协助企业监测生产进程。这些数据可能包括工作进度、生产速率、库存、质量、安全等。通过这些数据的可视化呈现&#xff0c;生产管理人员可以更快速地获得关于生产进程的信息&#xff0c;并能更快地做出决策…

如何将本地项目上传到Github的方法步骤

默认&#xff1a;已经安装好了git。 第一步&#xff1a;我们需要先创建一个本地的版本库&#xff08;其实也就是一个文件夹&#xff09;。 你可以直接右击新建文件夹&#xff0c;也可以右击打开Git bash命令行窗口通过命令来创建。 第二步&#xff1a;通过命令git init把这个…

深度分析MVC和MVVM:你在选择框架的时候应该注意什么?

&#x1f496; 作者简介&#xff1a;大家好&#xff0c;我是Zeeland&#xff0c;全栈领域优质创作者。&#x1f4dd; CSDN主页&#xff1a;Zeeland&#x1f525;&#x1f4e3; 我的博客&#xff1a;Zeeland&#x1f4da; Github主页: Undertone0809 (Zeeland) (github.com)&…

SpringCloudalibaba微服务工具集

版本: Hoxton SR6 1.什么是微服务 官网 In short, the microservice architectural(架构) style is an approach to developing a single application as a suite(系列) of small services, each running in its own process(进程) and communicating with lightweight mech…