uniapp和微信小程序 国际化

2020-11-04  本文已影响0人  小小不下雨

初始化npm工程

若项目之前未使用npm管理依赖(项目根目录下无package.json文件),先在项目根目录执行命令初始化npm工程:

npm init -y

npm install vue-i18n --save

下载vue-i18n后


image.png

新建common文件里建两个语言js


image.png

en.js

module.exports = {
    index: {
        hotTitle: 'Popular Recommend'
    },
    home: 'Home',
    mine: 'Mine',
}

zh.js

module.exports = {
    index: {
        hotTitle: '人气推荐'
    },
    home: '首页',
    mine: '我的',
}

在main.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'  

/**
 * 国际化
 */
Vue.config.productionTip = false
Vue.use(VueI18n)

const i18n = new VueI18n({  
  locale: 'zh-CN',  // 默认选择的语言
      messages: {
        'zh-CN': require('./common/lang/zh'),   // 中文语言包
        'en-US': require('./common/lang/en')    // 英文语言包
      }
}) 

Vue.prototype._i18n = i18n;

App.mpType = 'app'
const app = new Vue({
    i18n,
    ...App
})
app.$mount()

在App.vue里

onLaunch: function() {
            //检查语言类型
            var lan = 'zh'
             try {
                const res = uni.getSystemInfoSync();
                lan = res.language
            } catch (e) {
                console.log('error='+e)
            }
            console.log('lan='+lan); 
            
             if(lan == 'zh-Hans-CN' || lan=='zh' || lan=='zh_CN') {
                 this.$i18n.locale = 'zh-CN'
             }else{
                 this.$i18n.locale = 'en-US'
             }
}

在page中使用

    <text class="tit">{{$t('index.hotTitle')}}</text>
    <text class="tit2">{{$t('home')}}</text>


        data() {
            return {
                countText:this.$t('mine'),

            }
        },
上一篇下一篇

猜你喜欢

热点阅读