uniapp 实现多语言切换

先在项目安装 npm install vue-i18n

在根目录新建common/locales/zh.js和common/locales/en.js

//zh.js
export default {
	login: {
		title:'登录',
		register: '注册'
	}
}


//en.js
export default {
	login: {
		title:'Login',
		register: 'Register'
	}
}

在main.js引入

// 引入并使用vue-i18n
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)

// 引入语言包,注意路径
import Chinese from '@/common/locales/zh.js'; //简体中文
import English from '@/common/locales/en.js'; //英文

// 构造i18n对象
const i18n = new VueI18n({
	// 默认语言,这里的local属性,对应message中的cn、en属性
	locale: uni.getStorageSync('locale') || 'zh_CN',
	// 引入语言文件
	messages: {
		// 这里的属性名是任意的,您也可以把zh设置为cn等,只是后续切换语言时
		// 要标识这里的语言属性,如:this.$i18n.locale = zh|en|cn|xxx
		'zh_CN': Chinese,
		'en_US': English
	}
})

Vue.use(uView);
const app = new Vue({
	i18n,
	...App
})

页面使用index.vue

<view>
	//登录
	<view>{{$t('login.title')}}</view>
	//注册
	<view>{{$t('login.register')}}</view>
	//语言选择
	<view v-for="(item, index) in lans" :key="index" @click="onLans(index)">
		{{ item.name }}
	</view>
</view>


data(){
		lans: [{
						name: '中文'
					},
					{
						name: 'English'
					}
			]
},
onShow(){
	if (uni.getStorageSync('locale') == 'en_US') {
				this.$i18n.locale = 'en_US';
			} else {
				this.$i18n.locale = 'zh_CN';
			}
},
methods: {
//切换语言事件 
	onLans(index ){
		if (index == 0) {
					this.$i18n.locale = 'zh_CN';
					uni.setStorageSync('locale', 'zh_CN');
				} else if (index == 1) {
					this.$i18n.locale = 'en_US';
					uni.setStorageSync('locale', 'en_US');
				}
	}
}

完结撒花

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值