uniapp實現多語言切換


1.下載

npm install vue-i18n

2.創建語言包

3.在main.js中引入

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

const i18n = new VueI18n({
    locale: uni.getStorageSync('lang') == (undefined || "" || null) ?
        "zh" :
        uni.getStorageSync('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';
    uni.setStorageSync('lang', 'zh');
},
switchEn() {
    //英文
    this._i18n.locale = 'en';
    uni.setStorageSync('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
    });
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM