uniapp在移动开发中越来越火热,今天刚好开发了项目的国际化,期间查资料遇到了一些坑,所以我把我开发的实例完整的写一遍,希望对大家有所帮助。
一 、安装依赖包
在uniapp项目目录下安装i18n
npm install vue-i18n --save
二、main.js中引入
在main.js中引入i18n
import Vue from 'vue'
import App from './App'
import VueI18n from 'vue-i18n';
import Messages from './pages/api/language.js'
Vue.use(VueI18n);
Vue.config.productionTip = false;
const i18n = new VueI18n({
locale: 'zh-CN', //zh-CN en-US
messages:Messages //language中的语言包
})
Vue.prototype._i18n = i18n;
App.mpType = 'app'
const app = new Vue({
i18n,
...App
})
app.$mount()
二、language.js
export default {
'zh-CN':{
cpfw:'产品服务',
fwcx:'防伪查询',
qsrsym:'请输入溯源码或点击右侧图标扫码(必填)',
qsrfwm:'请输入防伪码或点击右侧图标扫码',
query:'查询',
zxkf:'在线客服',
cpxx:'产品选型',
cszx:'参数咨询',
azzx:'安装咨询',
shfw:'售后服务',
},
'en-US':{
cpfw:'Product service',
fwcx:'Anti-counterfeiting query',
qsrsym:'Please enter the source code or click the icon on the right to scan the code (required).',
qsrfwm:'Please enter the source code or click the icon on the right to scan the code.',
query:'Inquire',
zxkf:'Online service',
cpxx:'Product model',
cszx:'Parameter consultation',
azzx:'Installation consultation',
shfw:'After-sales service',
swzh:'Business support',
}
}
三、在homepage.vue主页面使用
1、js中使用
{
url: '../../static/1_01.png',
text:this.$t('cpfw'), //取值
}
2、在html中使用
<text class="text">{{$t('fwcx')}}</text>
<uni-section :title= "$t('fwcx')" class='bg-color' type="line"></uni-section>
<input class="uni-input" v-model="fangweiCode" focus :placeholder="$t('qsrfwm')" />
说明:在子页面中的html使用也是一样的,子页面js中$t(‘fwcx’)无效,引用应该是要用vue的mixin了吧
四、顶部导航双语
1、在主页面中顶部导航
uni.setNavigationBarTitle({
title:$t('fwcx')
})
2、子页面顶部导航
由于项目中子页面数据展示采用双语数据库,所以子页面需要展示的字段并不多,前边说过了,子页面html可以正常使用$t(‘abc’)来取值,够用了,顶部导航采用了页面跳转url传值。
从主页面把子页面的title传入子页面,在onload中拿到之后,用uni.setNavigationBarTitle 赋值也是可以的~
主页面跳转传值:
if(e == '/pages/web-view/tmsm'){
const append = '?title='+this.$t('cszx');
e = e + append;
}
uni.navigateTo({
url: e
})
子页面取值,并赋值顶部导航:
五、根据系统语言双语
在app.vue的onLaunch中,用uni.getSystemInfoSync()获取系统语言。
来吧,展示~