uni-app 如何语言国际化/多语言处理

应用内国际化处理

可以使用 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: 'zh-CN',  // 默认选择的语言
  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...',
		index: {
			navTitle: 'Face TV',
			more: 'more'
		},
		content: {
			derector: 'derector',
			protagonist: 'protagonist'
		},
		mine: {
			login: 'login',
			myCollection: 'My favorite'
		}
	},
	'zh-CN': {
		lang: 'zh',
		loading: '加载中...',
		index: {
			navTitle: '扫扫看电视',
			more: '更多'
		},
		content: {
			derector: '导演',
			protagonist: '主演'
		},
		mine: {
			login: '登录',
			myCollection: '我的收藏'
		}
	}
}

local 的值对应着一级 key en-USzh-CN,这里只简单的写了两种语言,en-US(其他语言同理)内部的 keyval 都由自己决定,比如我习惯根据不同页面会定义不同 keyindex 表示主页,content 代表内容页等

在需要的页面引用这些变量
比如在 index.vue 页面需要更改导航栏标题

uni.setNavigationBarTitle({
	title: this.$t('index.navTitle')
})

如果是在标签中绑定

<view class="cartu-more">{{$t('index.more')}}</view>
<view class="action">{{ $t("content.derector") }}</view>

检测系统语言并改变 locale 值
app.vueonLaunch 中使用 uni.getSystemInfoSync()

var lan = 'zh'
 try {
	const res = uni.getSystemInfoSync();
	lan = res.language
} catch (e) {
	console.log('error='+e)
}
console.log('lan='+lan); 
 if(lan == 'en') {
	 this.$i18n.locale = 'en-US'
 }
 if(lan == 'zh-Hans-CN' || lan=='zh') {
	 this.$i18n.locale = 'zh-CN'
 }

补充 Dcloud 官方文档

  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值