i18n.js 2.2 KB
Newer Older
1 2 3 4 5 6 7
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
8
}
9 10 11 12 13 14 15
let currentLang
if(i18nEnable){
	currentLang = uni.getStorageSync('CURRENT_LANG')
}else{
	currentLang = "zh-Hans"
}
console.log(uni.getStorageSync('CURRENT_LANG'),currentLang);
16
if (!currentLang) {
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
	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
48 49 50
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
51 52 53 54 55 56 57 58 59 60 61
const i18n = new VueI18n(i18nConfig)
// #endif

// #ifdef VUE3
import {
	createI18n
} from 'vue-i18n'
const i18n = createI18n(i18nConfig)
// #endif

export default i18n
62 63


64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
if(i18nEnable){
	console.log(1);
	let initLanguageAfter = () => {
		//获得定义的文字
		console.log($i18n('tabbar').split(','));
		function $i18n(e){
			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)
		//更新 uni-starter.config
		//agreements
		let agreementsTitle = $i18n('agreementsTitle').split(',')
		let agreements = uniStarterConfig.about.agreements
		agreements[0].title = agreementsTitle[0]
		agreements[1].title = agreementsTitle[1]
		uniStarterConfig.about.agreements = agreements
	}
	initLanguageAfter()
	uni.$on('changeLanguage', e => {
		console.log('changeLanguage', e);
		initLanguageAfter(e)
	})
}