1:起步
1: 安裝i18n依賴,npm install i18n --save-dev梨熙。
2: 也可以直接去下載 i18n的依賴js开镣,我這直接下載好了,直接拿去用 vue-i18n.js 提取碼: 8bjs
2:在根目錄下咽扇,跟components同級邪财,新建文件夾舅列,i18n。
3: 在剛新建的 i18n 文件夾下卧蜓,新建 lang 文件夾(也可以不用新建,看個人)把敞。
1: lang文件夾存放我們的語言包弥奸。
2: index.js 是對我們的語言包做處理。
3: vue-i18n.js 剛上面也有提奋早,如果你通過npm install 安裝了依賴盛霎,那么就不需要了。
4: index.js 處理我們的語言包
import Vue from 'vue';
import LangEn from './lang/en.js';
import LangCn from './lang/zh.js';
import VueI18n from './vue-i18n.js'(沒有通過npm) 或 import VueI18n from 'vue-i18n' (通過npm)
Vue.use(VueI18n);
// 去保存好的值
const system_key = uni.getStorageSync('system_key');
if(!system_key){
// 獲取設(shè)備信息
uni.getSystemInfo({
success: function(res) {
console.log(res)
uni.setStorageSync('system_key',res);
}
})
}
// 判斷獲取后的值是什么語言
let lang_cur = '';
switch(lang_cur){
case 'zh':
lang_cur = 'zh'
break;
case 'en':
lang_cur = 'en'
break;
}
// 實(shí)例化VueI18n對象
const i18n = new VueI18n({
// 默認(rèn)語言
locale: lang_cur || 'en',
// 兩種方式
messages: {
'en': require('./lang/en.js'),
'zh': require('./lang/zh.js')
}耽装,
messages: {
'en': LangEn,
'zh': LangCn
}
})
// 拋出去
export default i18n
5: 處理完之后愤炸,將index.js掛載到全局,也就是main.js中掉奄。
/**
* @note internationalization 國際化
* */
import i18n from './i18n/index.js';
Vue.prototype._i18n = i18n
App.mpType = 'app'
// 引入倉庫全局掛載
Vue.prototype.$store = store
const app = new Vue({
i18n,
store,
...App
})
app.$mount()
6: 在頁面中使用规个,以及在設(shè)置頁面切換不同的語言。
<template>
<view>
<tui-list-cell :hover="false" unlined :arrow="true" padding="30rpx 32rpx" :lineLeft="false" @tap="langClick">
<view class="tui-item-box">
<view class="tui-list-cell_name">{{$t('langChinese.lang')}}</view>
<view class="tui-right">{{ lang | filer() }}</view>
</view>
</tui-list-cell>
<!-- 語言篩選 -->
<tui-picker
:show="showActionSheetList"
:cancelText="$t('langChinese.cancel')"
:confirmText="$t('langChinese.confirm')"
:pickerData="languagePack"
:value="pickerValue"
@hide="hide"
@change="changePicker">
</tui-picker>
</view>
</template>
<script>
export default {
data(){
return {
name: this.$t('langChinese.cancel'),
lang: '',
showActionSheetList: false,
languagePack: [],
pickerValue: []
}
},
onLoad() {
// 進(jìn)入頁面獲取語言包
const system_key = uni.getStorageSync('system_key');
this.lang = system_key.language;
},
filters:{
filer(e){
let nameLang = '';
e == 'en' ? nameLang = 'English' : nameLang = '中文';
return nameLang
}
},
changePicker(e){
// 獲取緩存中的語言
const system_key = uni.getStorageSync('system_key');
// 通過switch 遍歷
switch (e.value) {
case 0:
system_key.language = this._i18n.locale = 'en'
break;
case 1:
system_key.language = this._i18n.locale = 'zh'
break;
}
this.lang = system_key.language;
uni.setStorageSync('system_key',system_key);
uni.switchTab({
url: "../../tabbar/index/index"
});
// title 動態(tài)渲染
uni.setNavigationBarTitle({
title: this.$t('langChinese.set')
});
},
hide(){
this.showActionSheetList = false;
},
}
</script>
7: 小結(jié)
1: 以上內(nèi)容就是有國際化需求提供參考姓建,
2: 如果大家有好的方式诞仓,方法,都可以討論速兔,
3: 希望能對你有幫助墅拭,