因为业务需求很多app都是可以多种语言进行切换的,以此来方便用户的使用
做语言的切换一定要开发开始的时候就规划好,不然确实太麻烦了,我是后期开发的语言切换,好多个页面都需要进行修改
- main.js中引入,注意如果是使用storage进行存储,几个平台是需要单独进行处理的,否则可能导致只能单个平台出现,我测试时是将几个平台的测试界面都打开的,大家写的时候最好也是这样操作,不然写完之后可能都不知道是什么原因导致页面显示不出来,最好是开启H5和手机模拟器,微信端的问题还是很少的
手机端是需要使用plus.storage来进行存储和获取的,H5端使用localStorage进行存储和获取,这个一定要注意,否则很可能不适用
-首先添加语言文件
- mian.js中引用
import VueI18n from 'vue-i18n'
Vue.use(VueI18n);
const i18n = new VueI18n({
// #ifdef MP
locale: 'zh-CN', //初始化,保证刷新页面也保留
// #endif
// #ifdef APP-PLUS
locale: plus.storage.getItem('locale') || 'zh-CN', //初始化,保证刷新页面也保留
// #endif
// #ifdef H5
locale: localStorage.getItem('locale') || 'zh-CN', //初始化,保证刷新页面也保留
// #endif
// 加载语言文件的内容
messages: {
'zh-CN': require('./locales/zh-CN.js').lang,
'en': require('./locales/en.js').lang
}
})
Vue.prototype._i18n = i18n
const app = new Vue({
i18n,
...App
})
- 语言切换按钮的处理,存储切换后的结果(这部分代码大家可以去插件市场搜索,有相应的插件),在做储存的时候也要记得进行多端的处理。
<view class="model" v-if="modelStatus">
<view class="selectlanguage">
<view @click="handove('zh-CN')">{{$t('login.simplified')}}</view>
<view @click="handove('en')">{{$t('login.english')}} </view>
</view>
</view>
export default {
data() {
return {
modelStatus:false
};
},
onShow(){
uni.setNavigationBarTitle({
title: this.$i18n.messages[this.$i18n.locale].person.settings
});
},
methods:{
selectlang(){
this.modelStatus=!this.modelStatus
},
handove(item){
this.$i18n.locale = item;
// #ifdef APP-PLUS
plus.storage.setItem('locale', item);
// #endif
// #ifdef H5
localStorage.setItem('locale', item);
// #endif
this.modelStatus=!this.modelStatus;
},
<style>
.model {
width: 100%;
height: 100vh;
background-color: rgba(0, 0, 0, 0.6);
position: fixed;
left: 0;
top: 0;
z-index: 100;
}
.selectlanguage{
width:393upx;
height: 400upx;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
position: absolute;
background: #fff;
z-index: 99;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding:50upx 0;
border-radius: 20upx;
}
.selectlanguage view{
height: 100upx;
line-height: 100upx;
color: #EABB76;
}
</style>
- 页面中的使用
- 如何修改底部导航栏和头部标题,建议放在onShow()中,网上部分是放在onload()中的,如果是登录前切换好是没问题的,如果你想在任何时候都可以切换的话,放onShow()是不会有什么问题的
onShow() {
// 修改底部导航
uni.setTabBarItem({
index: 0,
text: this.$i18n.messages[this.$i18n.locale].tabBar.home
});
// 修改头部标题
uni.setNavigationBarTitle({
title: this.$i18n.messages[this.$i18n.locale].tabBar.market
});
},