在上文我们提到许多知识点,现在我们来一一分析整理
一、多国语言支持
1、在main.js引入国际化 i18n.js。
官方说明,个人感觉LoginDemo的图际化比官方说明,更好理解。
import App from './App'
import i18n from './lang/i18n' //这是国际化模块
// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
i18n, //引入国际化
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import {
createSSRApp} from 'vue'
export function createApp() {
const app = createSSRApp(App)
app.use(i18n) //引入图际化
return {
app}
}
// #endif
2、lang/i18n.js,语言处理中心
import langEn from './en'
import zhHans from './zh-Hans'
import uniStarterConfig from '../uni-starter.config.js'
const {
i18n:{
enable:i18nEnable} }= uniStarterConfig
const messages = {
'en': langEn,
'zh-Hans': zhHans
}
let currentLang
if(i18nEnable){
currentLang = uni.getStorageSync('CURRENT_LANG')
}else{
currentLang = "zh-Hans"
}
// console.log(uni.getStorageSync('CURRENT_LANG'),currentLang);
if (!currentLang) {
if (uni.getLocale) {
console.log('获取应用语言:', uni.getLocale());
let language = 'en'
if (uni.getLocale() != 'en') {
language = 'zh-Hans'
}
uni.setStorageSync('CURRENT_LANG', language)
currentLang = language
} else {
uni.getSystemInfo({
success: function(res) {
console.log('获取设备信息:', res);
let language = 'zh-Hans'
if (res.language == 'en') {
language = 'en'
}
uni.setStorageSync('CURRENT_LANG', language)
currentLang = language
},
fail: (err) => {
console.error(err)
}
})
}
}
let i18nConfig = {
locale: currentLang, // set locale
messages // set locale messages
}
// #ifdef VUE2
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n(i18nConfig)
// #endif
// #ifdef VUE3
import {
createI18n
} from 'vue-i18n'
const i18n = createI18n(i18nConfig)
// #endif
export default i18n
if(i18nEnable){
console.log(`
你已开启多语言国际化,将自动根据语言获取【lang/en.js】或【lang/en.js】文件中配置的tabbar的值,
覆盖你在pages.json中的tabbar的值
如果你不需要多语言国际化,请打开配置文件uni-starter.config.js找到 -> i18n -> enable把值设置为false
`);
let initLanguageAfter = () => {
function $i18n(e){
// #ifdef VUE3
return i18n.global.messages[i18n.global.locale][e]
// #endif
return i18n.messages[i18n.locale][e]
}
setTimeout(function(){
//底部tabbar更新
$i18n('tabbar').split(',').forEach((text, index) => {
// console.log(text);
uni.setTabBarItem({
index,
text,
complete: e => {
// console.log("e: " + JSON.stringify(e));
}
})
})
},1)
}
initLanguageAfter()
uni.$on('changeLanguage', e => {
console.log('changeLanguage', e);
initLanguageAfter(e)
})
}
这里有几个知识点:
- 一次定义多个层级变量并初始化 const {i18n:{enable:i18nEnable} }= uniStarterConfig
- 当前系统的语言,定义在本地缓存中 uni.getStorageSync(‘CURRENT_LANG’)
- 如何取得本项目的语言 uni.getLocale(),只有两种结果en和非en(zh-Hans)
- 把语言保存到本地缓存中,uni.setStorageSync(‘CURRENT_LANG’, language)
- uni.getLocale是什么梗
<相当于存在测试>
?uni.getLocale()明明是一个函数,为什么可以这样用????- 如何取得系统信息?uni.getSystemInfo
- 如何从系统信息找到语言? res.language = zh-Hans,en
- 当操作系统的语言与app默认语言不一样时,会产生changeLanguage事件, uni.$on(‘changeLanguage’, e => { 是什么?是改变语言的事件
3、uni.getSystemInfo实测
{
"SDKVersion": "",
"appId": "__UNI__8744A03",
"appLanguage": "zh-Hans",
"appName": "LoginDemo",
"appVersion": "13.8.12",
"appVersionCode": 130812,
"appWgtVersion": "1.0.0",
"brand": "xiaomi",
"browserName": "chrome",
"browserVersion": "87.0.4280.101",
"deviceBrand": "xiaomi",
"deviceId": "F52F728CC0B22BF0E02CC67AC406E07E",
"deviceModel": "M2006C3LC",
"deviceOrientation": "portrait",
"devicePixelRatio": 2,
"deviceType": "phone",
"errMsg": "getSystemInfo:ok",
"language": "zh-CN",
"model": "M2006C3LC",
"oaid": "6131660a87a52a85",
"osAndroidAPILevel": 29,
"osLanguage": "zh-CN",
"osName": "android",
"osTheme": "light",
"osVersion": "10",
"pixelRatio": 2,
"platform": "android",
"romName": "MIUI",
"romVersion": "V125",
"safeArea": {
"left": 0,
"right": 360,
"top": 28,
"bottom": 800,
"width": 360,
"height": 772
},
"safeAreaInsets": {
"top": 28,
"right": 0,
"bottom": 0,
"left": 0
},
"screenHeight": 800,
"screenWidth": 360,
"statusBarHeight": 28,
"system": "Android 10",
"ua": "Mozilla/5.0 (Linux; Android 10; M2006C3LC Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/87.0.4280.101 Mobile Safari/537.36 uni-app (Immersed/27.5)",
"uniCompileVersion": "3.8.12",
"uniPlatform": "app",
"uniRuntimeVersion": "3.8.12",
"version": "1.9.9.81924",
"windowBottom": 0,
"windowHeight": 800,
"windowTop": 0,
"windowWidth": 360
}
这个函数与 官网 有一些差别,也许是老了。
但是 uni.$on(‘changeLanguage’,红米是无法测试的,但是oppo可以!
4、lang/en.js详情
export default {
tabbar:'List,Grid,contacts,Mine',
agreementsTitle:'User service agreement,Privacy policy',
common: {
wechatFriends: "friends",
wechatBbs: "bbs",
weibo: "weibo",
more: "more",
agree:"agree",
copy: "copy",
wechatApplet: "applet",
cancelShare: "cancel sharing",
updateSucceeded: "update succeeded",
phonePlaceholder: "Please enter your mobile phone number",
verifyCodePlaceholder: "Please enter the verification code",
newPasswordPlaceholder: "Please enter a new password",
confirmNewPasswordPlaceholder: "Please confirm the new password",
confirmPassword: "Please confirm the password",
verifyCodeSend: "Verification code has been sent to via SMS",
passwordDigits: "The password is 6 - 20 digits",
getVerifyCode: "Get Code",
noAgree: "You have not agreed to the privacy policy agreement",
gotIt: "got it",
login: "sign in",
error: "error",
complete: "complete",
submit: "Submit",
formatErr: "Incorrect mobile phone number format",
sixDigitCode: "Please enter a 6-digit verification code",
resetNavTitle:"Reset password"
},
list: {
inputPlaceholder: "Please enter the search content",
},
search: {
cancelText: "cancel",
searchHistory: "search history",
searchDiscovery: "search discovery",
deleteAll: "delete all",
delete: "delete",
deleteTip: "Are you sure to clear the search history ?",
complete: "complete",
searchHiddenTip: "Current search found hidden",
},
grid: {
grid: "Grid Assembly",
visibleToAll: "Visible to all",
invisibleToTourists