1. 程式人生 > 實用技巧 >uniapp實現多語言切換

uniapp實現多語言切換

  • 本文只示例App端,H5端把plus.storage換成localStorage即可,如果要進行多語言切換,建議一開始就規劃好,做翻譯的時候最好開啟模擬器

1.下載

npm install vue-i18n

2.建立語言包

3.在main.js中引入

import VueI18n from "vue-i18n";
Vue.use(VueI18n);

const i18n = new VueI18n({
    locale: plus.storage.getItem('lang') == (undefined || "" || null) ?
        "zh" :
        plus.storage.getItem(
'lang'), messages: { zh: require("./static/lang/text-zh.json"), en: require("./static/lang/text-en.json") } }); Vue.prototype._i18n = i18n const app = new Vue({ i18n, ...App }) app.$mount()

4.語言切換

<button @click="switchZh">中文簡體</button>
<button @click="switchEn">English</button>

switchZh() {
    
//中文 this._i18n.locale = 'zh'; plus.storage.setItem('lang', 'zh'); }, switchEn() { //英文 this._i18n.locale = 'en'; plus.storage.setItem('lang', 'en'); }

4.在元件中使用

<view>{{ $t('home.home') }}</view>

5.修改底部導航欄和標題

onShow() {
    uni.setNavigationBarTitle({// 修改頭部標題
        title: this
.$i18n.messages[this.$i18n.locale].home.title }); uni.setTabBarItem({// 修改底部導航 index: 0, text: this.$i18n.messages[this.$i18n.locale].home.nav }); }