uniapp vue-i18n国际化语言随机切换

uniapp vue-i18n国际化语言随机切换

npm安装

npm install vue-i18n --save

在main.js中引入

import Vue from 'vue';
import App from './App';
import VueI18n from 'vue-i18n'  
import messages from './commom/lang.js'
Vue.use(VueI18n)  
Vue.config.productionTip = false;

const i18n = new VueI18n({
    
      
 locale: localStorage.getItem('language'),  // 获取localStorage中存入的语言状态
 // locale:'en-US',
 messages
})  
App.mpType = 'app';
Vue.prototype.$i18n = i18n  
const app = new Vue({
    
    
	i18n,
    ...App
});
app.$mount();

其中改变 locale 的取值可以改变语言的类型,messages 的内容我放到一个独立的lang.js 文件,便于维护,其中的内容如下

export default {
    
    
	// 英语
	'en-US': {
    
    
		lang: 'en',
		loading: 'loading...',
		turnTable:{
    
    
			rulesBtn:'Rules',
			winningList:'List',
			sorry:'Sorry',
			vip:'VIP',
		},
		chances:{
    
    
			recharge:'Recharge',
			recharge1:'$1.99',
			recharge2:'$4.99',
			recharge3:'$9.99',
			recharge4:'>$19.99',
			cions:'Coins',
			cions1:'199',
			cions2:'500',
			cions3:'1000',
			cions4:'>2000',
			reWards:'Rewards',
			reWards1:'+1 turntable',
			reWards2:'+2 turntable',
			reWards3:'+5 turntable',
			reWards4:'+10 turntable',
			name:'has won',
			
		},
		rule:{
    
    
			eventsTime:'1. Event Time:',
			until:'5/1-5/31',
			rules:'2. Rules',
		}
	},
	// 阿拉伯语言
	'ar': {
    
    
		lang: 'ar',
		turnTable:{
    
    
			rulesBtn:'القواعد',
			winningList:'قائمة',
			sorry:'آسف',
			vip:'VIP',
		},
		chances:{
    
    
			reWards:'مكافآت',
			reWards1:'دورة حظ +1',
			reWards2:'دورة حظ +2',
			reWards3:'دورة حظ +5',
			reWards4:'دورة حظ +10',
			name:'تمت',
		},
		rule:{
    
    
			eventsTime:'1.وقت الحدث',
			until:'1 مايو - 31 مايو',
			rules:'2.القواعد',
		}
		
	},
}

local 的值对应着一级 key ar和 en-US,这里只简单的写了两种语言

接下来就是简单的使用了 在js方法中或者data中使用

title: this.$t('turnTable.rulesBtn')

在标签中使用如下

<view class="cartu-more">{
    
    {
    
    $t('turnTable.rulesBtn')}}</view>

我这里使用的是var ual = navigator.languages; 获取手机的系统语言
然后将获取到的语言 存入缓存中 在main.js 中引入获取缓存中的语言再去改变 local的值 渲染页面

在这里有一个uniapp的坑 特别提醒一下 在index页面存入语言环境 在main.js取出 会出现main.js早执行的问题所以 第一次改变语言环境,会出现切换不及时的问题 所以在存入之后加上this.$i18n.locale = language;

localStorage.setItem("language",this.locale)
this.$i18n.locale = language;

大概就是这样

猜你喜欢

转载自blog.csdn.net/ranmoli/article/details/116457612