uniapp-Vue项目如何实现国际化,实现多语言切换,拒绝多套开发,一步到位,看这篇就够

本文主要是介绍uniapp-Vue项目如何实现国际化,实现多语言切换,拒绝多套开发,一步到位,看这篇就够,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一  安装

找到自己的项目,输入cmd进入命令行,输入安装命令,点击回车进行下载:

npm install vue-i18n@next

下载完将在项目的配置文件中看到:

二  使用

2.1 在项目中创建一个文件夹如:lang 用于存放不同语言的包。这些语言文件通常为JSON格式

2.2 在项目main.js文件中引入并初始化VueI18n。这包括引入上述创建的语言文件,并配置VueI18n:

import i18n from '@/lang/index' // 引入国际化配置//这行代码是 Vue 2 的标准写法,不要使用 Vue 3 的 createApp 语法。
// Vue.prototype.$store = store
// Vue.config.productionTip = false// 创建 Vue 实例,并注入 i18n
const app = new Vue({i18n, // 注入国际化store,render: h => h(App)
})

在lang下创建 en.js  zh.js  index.js 分别写入下面代码

index.js

import Vue from 'vue';
import VueI18n from 'vue-i18n';
import zh from './zh';
import en from './en';
// 需要什么语言都要导入// 使用 Vue 2 的 VueI18n
Vue.use(VueI18n);const i18n = new VueI18n({locale: localStorage.getItem('language') || 'zh', // 默认语言为中文messages: {zh,en,},
});export default i18n;

英文包:en.js

//en.js
export default {language:{// 这里面放 所有的英文替换词}
}

中文包:zh.js

//en.js
export default {language:{// 这里面放 所有的中文替换词}
}

三 以登录界面为例

3.1 首先找好图标,对界面加个图标做个触发

		// 切换语言 逻辑处理switchLanguage() {const newLanguage = this.$i18n.locale === 'zh' ? 'en' : 'zh';this.$i18n.locale = newLanguage;localStorage.setItem('language', newLanguage);this.languageIcon = newLanguage === 'en' ? '/static/china.png' : '/static/en.png';},

3.2 对页面需要国际化的每个组件都可以使用 $t 方法来获取国际化文本。

在 zh.js 和 en.js 文件中添加对应的语言内容

// en.js 登录内容如下export default {language: {//login 登录界面welcome: "Smart Education Platform",phonePlaceholder: "Please enter your phone number",codePlaceholder: "Please enter the verification code",getCode: "Get Code",login: "Login",cancelLogin: "Cancel Login",loginSuccess: "Login Successful",phoneError: "Invalid phone number format!",phoneEmpty: "Phone number cannot be empty!",codeError: "Invalid verification code format!",codeEmpty: "Verification code cannot be empty!",codeSent: "Verification code sent",loginFailed: "Login failed, please try again",}
}
// zh.js 登录界面元素需国际化的内容如下
export default {language: {// login 登录界面welcome: "智教平台",phonePlaceholder: "请输入手机号",codePlaceholder: "请输入验证码",getCode: "获取验证码",login: "登 录",cancelLogin: "取消登录",loginSuccess: "登录成功",phoneError: "手机号格式不正确!",phoneEmpty: "手机号不能为空!",codeError: "验证码格式不正确!",codeEmpty: "验证码不能为空!",codeSent: "验证码已发送",loginFailed: "登录失败,请重试",}
}

其他页面同理.只需要都写在对应的语言包文件下进行说明即可

同理也可以添加其它语言,做好语言选择的切换

界面完整代码:

<template><view class="tp-login-box tp-flex tp-flex-col tp-box-sizing"><!-- 语言切换按钮 --><view class="language-switch"><image :src="languageIcon" @tap="switchLanguage" class="language-icon" /></view><view class="tp-pd-t-b-30"></view><view class="tp-flex tp-login-welcome tp-flex-col tp-mg-t-b-50"><view class="fishTitle">{{ $t('language.welcome') }}</view><!-- 添加的Logo --><view class="tp-mg-t-b-20"><image src="/static/image/Logo.png" alt="logo" class="logo" /></view></view><!-- 手机号输入框 --><viewclass="tp-ipt tp-box-sizing tp-mg-t-b-20 tp-pd-t-b-15 tp-pd-l-r-30 tp-flex tp-flex-row tp-flex-j-l tp-flex-a-c":class="{'shake': phoneError}"><view class="inputicon"><image src="/static/shoujihao.png" alt=""></view><input type="text" placeholder-class="tp-plc" :placeholder="$t('language.phonePlaceholder')"v-model="phoneNumber" @blur="validatePhoneNumber" /></view><view v-if="phoneError" class="error-msg">{{ phoneErrorMsg }}</view><!-- 验证码输入框 --><viewclass="tp-ipt tp-box-sizing tp-mg-t-b-20 tp-pd-t-b-15 tp-pd-l-r-30 tp-flex tp-flex-row tp-flex-j-l tp-flex-a-c":class="{'shake': codeError}"><view class="inputicon"><image src="/static/yanzhengma-.png" alt=""></view><input type="text" placeholder-class="tp-plc" :placeholder="$t('language.codePlaceholder')"v-model="verificationCode" @blur="validateVerificationCode" /><view class="inputcode" @tap="requestVerificationCode">{{ $t('language.getCode') }}</view></view><view v-if="codeError" class="error-msg">{{ codeErrorMsg }}</view><!-- 登录按钮 --><view class="btn"><button class="tp-btn tp-mg-t-50" :loading="loading"@tap="doLoginSubmit">{{ $t('language.login') }}</button></view><view class="tp-getpwd tp-mg-t-40 tp-flex tp-flex-row tp-flex-j-c tp-flex-a-c" @tap="doLoginCancel">{{ $t('language.cancelLogin') }}</view><!-- 授权登录 --><uni-popup ref="authPopup" type="bottom"><authorize @getuserinfo="getAuth" @cancel="toCloseLogin"></authorize></uni-popup><!-- 登录成功提示框 --><uni-popup ref="successPopup" type="center" :mask="true" :maskClick="false"><view class="popup-content">{{ $t('language.loginSuccess') }}</view></uni-popup></view>
</template><script>export default {data() {return {loading: false, // 按钮的加载状态phoneNumber: '', // 存储用户的手机号verificationCode: '', // 存储验证码phoneError: false, // 手机号输入框错误标记phoneErrorMsg: '', // 手机号错误信息codeError: false, // 验证码输入框错误标记codeErrorMsg: '', // 验证码错误信息languageIcon: localStorage.getItem('language') === 'en' ? '/static/china.png' : '/static/en.png' // 语言切换图标}},methods: {// 切换语言switchLanguage() {const newLanguage = this.$i18n.locale === 'zh' ? 'en' : 'zh';this.$i18n.locale = newLanguage;localStorage.setItem('language', newLanguage);this.languageIcon = newLanguage === 'en' ? '/static/china.png' : '/static/en.png';},// 验证手机号输入框validatePhoneNumber() {const phoneRegex = /^1[3-9]\d{9}$/;if (!this.phoneNumber) {this.phoneError = true;this.phoneErrorMsg = this.$t('language.phoneEmpty');return false;} else if (!phoneRegex.test(this.phoneNumber)) {this.phoneError = true;this.phoneErrorMsg = this.$t('language.phoneError');return false;}this.phoneError = false;this.phoneErrorMsg = '';return true;},// 验证验证码输入框validateVerificationCode() {const codeRegex = /^\d{4}$/; // 假设验证码为4位数字if (!this.verificationCode) {this.codeError = true;this.codeErrorMsg = this.$t('language.codeEmpty');return false;} else if (!codeRegex.test(this.verificationCode)) {this.codeError = true;this.codeErrorMsg = this.$t('language.codeError');return false;}this.codeError = false;this.codeErrorMsg = '';return true;},// 请求验证码的APIrequestVerificationCode() {if (!this.validatePhoneNumber()) return;// 调用发送验证码的APIuni.request({url: 'http://192.168.0.180:8090/v1/api/system/send_captcha', // 发送验证码的API地址method: 'POST',data: {phone: this.phoneNumber // 传递手机号},success: (res) => {console.log(res.data);if (res.data.code == 2000) {this.codeErrorMsg = this.$t('language.codeSent');this.codeError = true;} else {this.codeErrorMsg = res.data.message || this.$t('language.loginFailed');this.codeError = true;}},fail: (err) => {this.codeErrorMsg = this.$t('language.loginFailed');this.codeError = true;}});},// 处理登录过程doLoginSubmit() {if (!this.validatePhoneNumber() || !this.validateVerificationCode())return;this.loading = true;// 调用登录的APIuni.request({url: 'http://192.168.0.180:8090/v1/api/system/login', // 登录的API地址method: 'POST',header: {'Content-Type': 'application/json'},data: {phone: this.phoneNumber, // 传递手机号code: this.verificationCode // 传递验证码},success: (res) => {console.log(res.data);if (res.data.code == 2000) {uni.setStorageSync('access_token', res.data.data.token); // 存储访问令牌this.$refs.successPopup.open(); // 显示登录成功提示框setTimeout(() => {uni.switchTab({url: '/pages/deviceManage/deviceManage' // 登录成功后跳转到首页});}, 1000);} else {this.phoneErrorMsg = res.data.message || this.$t('language.loginFailed');this.phoneError = true;}},fail: (err) => {this.phoneErrorMsg = this.$t('language.loginFailed');this.phoneError = true;},complete: () => {this.loading = false;}});},// 取消登录并返回上一页doLoginCancel() {uni.navigateBack(-1);},}}
</script><style>@import url("@/common/login.css");.language-switch {position: absolute;top: 20px;right: 20px;z-index: 100;}.language-icon {width: 30px;height: 30px;}/* 抖动动画 */@keyframes shake {0%,100% {transform: translateX(0);}20%,60% {transform: translateX(-10px);}40%,80% {transform: translateX(10px);}}.shake {animation: shake 0.5s ease;}.error-msg {color: red;font-size: 12px;text-align: center;margin-top: -10px;margin-bottom: 10px;}.popup-content {font-size: 18px;color: #000;padding: 20px;text-align: center;}
</style>

这篇关于uniapp-Vue项目如何实现国际化,实现多语言切换,拒绝多套开发,一步到位,看这篇就够的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1114416

相关文章

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima