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
    });
}

 

posted @ 2020-11-13 11:42  无痕-范特西  阅读(6963)  评论(0编辑  收藏  举报