本文主要是介绍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项目如何实现国际化,实现多语言切换,拒绝多套开发,一步到位,看这篇就够的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!